2 回答

TA貢獻1809條經驗 獲得超8個贊
生成的協議緩沖區文件tf.saved_model.save
不包含GraphDef
消息,而是包含一個SavedModel
.?您可以在 Python 中遍歷它SavedModel
以獲取其中的嵌入圖,但這不會立即用作凍結圖,因此正確處理它可能很困難。取而代之的是,C++ API 現在包含一個LoadSavedModel
調用,允許您從目錄加載整個保存的模型。它應該看起來像這樣:
#include <iostream>
#include <...>? // Add necessary TF include directives
using namespace std;
using namespace tensorflow;
int main()
{
? ? // Path to saved model directory
? ? const string export_dir = "...";
? ? // Load model
? ? Status s;
? ? SavedModelBundle bundle;
? ? SessionOptions session_options;
? ? RunOptions run_options;
? ? s = LoadSavedModel(session_options, run_options, export_dir,
? ? ? ? ? ? ? ? ? ? ? ?// default "serve" tag set by tf.saved_model.save
? ? ? ? ? ? ? ? ? ? ? ?{"serve"}, &bundle));
? ? if (!.ok())
? ? {
? ? ? ? cerr << "Could not load model: " << s.error_message() << endl;
? ? ? ? return -1;
? ? }
? ? // Model is loaded
? ? // ...
? ? return 0;
}
從這里開始,您可以做不同的事情。也許您最愿意使用 將保存的模型轉換為凍結圖FreezeSavedModel,這應該讓您可以像以前一樣做事:
GraphDef frozen_graph_def;
std::unordered_set<string> inputs;
std::unordered_set<string> outputs;
s = FreezeSavedModel(bundle, &frozen_graph_def,
? ? ? ? ? ? ? ? ? ? ?&inputs, &outputs));
if (!s.ok())
{
? ? cerr << "Could not freeze model: " << s.error_message() << endl;
? ? return -1;
}
否則,您可以直接使用保存的模型對象:
// Default "serving_default" signature name set by tf.saved_model_save
const SignatureDef& signature_def = bundle.GetSignatures().at("serving_default");
// Get input and output names (different from layer names)
// Key is input and output layer names
const string input_name = signature_def.inputs().at("my_input").name();
const string output_name = signature_def.inputs().at("my_output").name();
// Run model
Tensor input = ...;
std::vector<Tensor> outputs;
s = bundle.session->Run({{input_name, input}}, {output_name}, {}, &outputs));
if (!s.ok())
{
? ? cerr << "Error running model: " << s.error_message() << endl;
? ? return -1;
}
// Get result
Tensor& output = outputs[0];

TA貢獻2021條經驗 獲得超8個贊
我找到了以下問題的解決方案:
g = tf.Graph()
with g.as_default():
# Create model
inputs = tf.keras.Input(...)
x = tf.keras.layers.Conv2D(1, (1,1), padding='same')(inputs)
# Done creating model
# Optionally get graph operations
ops = g.get_operations()
for op in ops:
print(op.name, op.type)
# Save graph
tf.io.write_graph(g.as_graph_def(), 'path', 'filename.pb', as_text=False)
添加回答
舉報