要在C語(yǔ)言中調(diào)用TensorFlow模型,可以使用TensorFlow C API。以下是一個(gè)簡(jiǎn)單的示例代碼:
#include <stdio.h>
#include <tensorflow/c/c_api.h>
int main() {
TF_Graph* graph = TF_NewGraph();
TF_Status* status = TF_NewStatus();
// Load the SavedModel
TF_SessionOptions* session_options = TF_NewSessionOptions();
TF_Buffer* run_options = NULL;
const char* tags = "serve";
int ntags = 1;
TF_Session* session = TF_LoadSessionFromSavedModel(session_options, run_options, "path_to_saved_model", &tags, ntags, graph, NULL, status);
if (TF_GetCode(status) != TF_OK) {
fprintf(stderr, "Error loading model: %s\n", TF_Message(status));
return -1;
}
// Create input tensor
const int64_t dims[2] = {1, 784};
TF_Tensor* input_tensor = TF_AllocateTensor(TF_FLOAT, dims, 2, 784 * sizeof(float));
// Fill input tensor with data
// Create output tensor
TF_Output output;
output.oper = TF_GraphOperationByName(graph, "output");
output.index = 0;
TF_Tensor* output_tensor = TF_NewTensor(TF_FLOAT, dims, 2, 10 * sizeof(float), data, 10, &noop_deallocator, 0);
// Run the session
TF_Tensor* outputs[1] = {output_tensor};
TF_SessionRun(session, NULL, NULL, &input_tensor, outputs, 1, NULL, 0, NULL, 0, NULL, status);
if (TF_GetCode(status) != TF_OK) {
fprintf(stderr, "Error running model: %s\n", TF_Message(status));
return -1;
}
// Get the output values
float* output_data = TF_TensorData(output_tensor);
for (int i = 0; i < 10; i++) {
printf("Output value %d: %f\n", i, output_data[i]);
}
// Clean up
TF_CloseSession(session, status);
TF_DeleteSession(session, status);
TF_DeleteSessionOptions(session_options);
TF_DeleteGraph(graph);
TF_DeleteStatus(status);
return 0;
}
請(qǐng)注意,這只是一個(gè)簡(jiǎn)單的示例代碼,實(shí)際使用時(shí)需要根據(jù)自己的模型和數(shù)據(jù)進(jìn)行適當(dāng)?shù)男薷?。另外,需要確保正確鏈接TensorFlow C庫(kù)和頭文件。