溫馨提示×

c++如何調用tensorflow模型

小億
277
2024-04-16 13:39:05
欄目: 編程語言

要在C++中調用TensorFlow模型,可以使用TensorFlow C++ API。以下是一個簡單的示例代碼,演示如何加載和運行一個TensorFlow模型:

#include <iostream>
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/framework/tensor.h"

using namespace std;
using namespace tensorflow;

int main() {
  // 創建一個新的會話
  Session* session;
  Status status = NewSession(SessionOptions(), &session);
  if (!status.ok()) {
    cerr << status.ToString() << endl;
    return 1;
  }

  // 讀取模型文件
  GraphDef graph_def;
  status = ReadBinaryProto(Env::Default(), "path/to/your/model.pb", &graph_def);
  if (!status.ok()) {
    cerr << status.ToString() << endl;
    return 1;
  }

  // 將模型加載到會話中
  status = session->Create(graph_def);
  if (!status.ok()) {
    cerr << status.ToString() << endl;
    return 1;
  }

  // 創建輸入 tensor
  Tensor input(DT_FLOAT, TensorShape({1, 2}));
  auto input_tensor = input.flat<float>();
  input_tensor(0) = 1.0;
  input_tensor(1) = 2.0;

  // 運行模型
  vector<pair<string, Tensor>> inputs = {{"input", input}};
  vector<Tensor> outputs;
  status = session->Run(inputs, {"output"}, {}, &outputs);
  if (!status.ok()) {
    cerr << status.ToString() << endl;
    return 1;
  }

  // 輸出結果
  auto output_tensor = outputs[0].flat<float>();
  cout << "Output: " << output_tensor(0) << endl;

  // 關閉會話
  session->Close();

  return 0;
}

在這個示例中,我們首先創建一個新的會話,然后讀取模型文件并將模型加載到會話中。接下來,我們創建輸入tensor,將輸入數據填充到tensor中,并通過session->Run()方法來運行模型。最后,我們輸出模型的預測結果并關閉會話。

請注意,以上示例代碼僅供參考,實際應用中可能需要根據具體模型和數據進行適當的調整。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女