TensorFlow C API加载.pb模型遇localhost容器不存在错误,求C实现变量初始化方案
C语言调用TensorFlow C API加载Keras .pb模型解决变量未初始化错误
错误信息
Failed precondition: Error while reading resource variable value_dense_2/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/value_dense_2/bias) [[{{node nnue_model/value_dense_2/BiasAdd/ReadVariableOp}}]] [[StatefulPartitionedCall/_35]]
问题本质
该错误源于模型内的变量未完成初始化,对应Python中通过tf.global_variables_initializer()初始化全局变量并运行操作的解决方案,在C语言中需通过TensorFlow C API完成等价操作。
C语言实现方案
在TensorFlow C API中,需完成以下步骤初始化变量:
- 加载模型图并创建会话后,查找全局变量初始化操作节点(通常节点名为
init或global_variables_initializer); - 创建并运行该初始化操作的会话任务。
代码示例
#include <tensorflow/c/c_api.h> #include <stdio.h> #include <stdlib.h> // 辅助函数:读取二进制模型文件 TF_Buffer* ReadBinaryFile(const char* filename, TF_Status* status) { FILE* f = fopen(filename, "rb"); if (f == NULL) { TF_SetStatus(status, TF_NOT_FOUND, "Failed to open model file"); return NULL; } fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); void* data = malloc(fsize); fread(data, 1, fsize, f); fclose(f); TF_Buffer* buf = TF_NewBuffer(); buf->data = data; buf->length = fsize; buf->data_deallocator = free; return buf; } int main() { // 初始化TensorFlow资源 TF_Graph* graph = TF_NewGraph(); TF_Status* status = TF_NewStatus(); TF_SessionOptions* sess_opts = TF_NewSessionOptions(); // 加载.pb模型文件(替换为你的模型路径) TF_Buffer* model_buf = ReadBinaryFile("your_model.pb", status); if (TF_GetCode(status) != TF_OK) { fprintf(stderr, "%s\n", TF_Message(status)); return 1; } TF_ImportGraphDefOptions* import_opts = TF_NewImportGraphDefOptions(); TF_GraphImportGraphDef(graph, model_buf, import_opts, status); TF_DeleteImportGraphDefOptions(import_opts); TF_DeleteBuffer(model_buf); // 创建会话 TF_Session* session = TF_NewSession(graph, sess_opts, status); TF_DeleteSessionOptions(sess_opts); if (TF_GetCode(status) != TF_OK) { fprintf(stderr, "Failed to create session: %s\n", TF_Message(status)); return 1; } // 获取全局变量初始化操作节点 TF_Operation* init_op = TF_GraphOperationByName(graph, "init"); if (init_op == NULL) { init_op = TF_GraphOperationByName(graph, "global_variables_initializer"); } if (init_op == NULL) { fprintf(stderr, "Failed to find initialization operation node\n"); goto cleanup; } // 运行初始化操作 TF_Run(session, NULL, NULL, NULL, 0, &init_op, NULL, 0, NULL, 0, NULL, status); if (TF_GetCode(status) != TF_OK) { fprintf(stderr, "Failed to run init operation: %s\n", TF_Message(status)); goto cleanup; } // 此处添加模型推理代码 // ... cleanup: // 释放资源 TF_DeleteSession(session, status); TF_DeleteGraph(graph); TF_DeleteStatus(status); return 0; }
注意事项
- 若模型导出时未包含初始化节点,需在Python环境中先运行变量初始化,再导出为.pb文件;
- 可通过TensorBoard查看模型图结构,确认初始化操作的实际节点名称。
内容的提问来源于stack exchange,提问作者Gustasvs
相关产品推荐
相关产品推荐

