[英]Different prediction of Tensorflow in Python and C-API with SavedModel
[英]Accessing input and output tensors of a tensorflow 2.0 SavedModel via the C API
我無法從加載 C_API 的 tensorflow 2.0 SavedModel 運行推理,因為我無法按名稱訪問輸入和 output 操作。
我通過 TF_LoadSessionFromSavedModel(...) 成功加載了 session:
#include <tensorflow/c/c_api>
...
TF_Status* status = TF_NewStatus();
TF_Graph* graph = TF_NewGraph();
TF_Buffer* r_opts = TF_NewBufferFromString("",0);
TF_Buffer* meta_g = TF_NewBuffer();
TF_SessionOptions* opts = TF_NewSessionOptions();
const char* tags[] = {"serve"};
TF_Session* session = TF_LoadSessionFromSavedModel(opts, r_opts, "saved_model/tf2_model", tags, 1, graph, meta_g, status);
if ( TF_GetCode(status) != TF_OK ) exit(-1); //does not happen
但是,嘗試使用以下方法設置輸入和 output 張量時出現錯誤:
TF_Operation* inputOp = TF_GraphOperationByName(graph, "input"); //works with "serving_default_input"
TF_Operation* outputOp = TF_GraphOperationByName(graph, "prediction"); //does not work
我作為 arguments 傳遞的名稱被分配給輸入和 output keras 層的已保存圖形 Z20F35E630F 未加載到graph
,但 6 運行saved_model_cli
(按照此處的 tf SavedModel 教程)顯示具有這些名稱的 Tenor 存在於SignatureDef
serving_default
下,所以我想我需要將serving_default
實例化為一個圖形(換句話說,根據簽名創建一個圖形),但是我找不到使用 C API 的方法。
Note that tensorflows's C_API test uses C++ tensorflow/core/ functionality to load a signature definition map from the metagraph and uses it to find input and output operation names, but I would like to avoid the dependency on C++.
另請注意,按名稱訪問操作適用於frozen.pb 圖,但此格式已被棄用。
提前感謝您的任何想法和提示!
Currently (as of May 2020) the Tensorflow C API doesn't officially support the SavedModel ( tensorflow 2.0 ) format, even though they will probably release the functionality soon .
無論如何,您可以使用在導出 model 時定義的默認SignatureDefs,並使用saved_model_cli工具查找輸入和 output 張量的名稱。
假設您使用保存了 model
model.save('/path/to/model/folder')
然后,您打開 bash 並執行
cd /python/folder/bin/
saved_model_cli show --dir /path/to/model/folder --tag_set serve --signature_def serving_default
( saved_model_cli
的實際位置不同,但在bin/文件夾下使用anaconda時默認安裝)
默認情況下它會產生類似的東西:
serving_default
The given SavedModel SignatureDef contains the following input(s):
inputs['graph_input'] tensor_info:
dtype: DT_DOUBLE
shape: (-1, 28, 28)
name: serving_default_graph_input:0
The given SavedModel SignatureDef contains the following output(s):
outputs['graph_output'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 10)
name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict
在這種情況下, serving_default_graph_input是輸入張量名稱, StatefulPartitionedCall是 output 張量名稱。 然后,您可以使用TF_GraphOperationByName()
加載它們。
With C API support for Tensorflow 2 you'd be able to save the model with a set of defined SignatureDefs and then load the desired concrete_function()
, without having to worry about tensor names. 但是,這種當前方法應該仍然有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.