![](/img/trans.png)
[英]In Tensorflow's C++ API, how do I use an Eigen Tensor to set my Tensorflow Tensor?
[英]How do I set the value of an input tensor in c++?
我正試圖通過ios上經過預先訓練的模型運行樣本。 session-> Run()將張量作為輸入作為我的理解。 我已經初始化了張量,但我如何設置它的值? 我沒有太多使用C ++的經驗。
我已成功創建了一個接受3維張量形狀{1,1,10}的測試模型。
我從Tensorflow的簡單示例中提取了以下代碼行來創建輸入張量。
tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({1,1,10}));
從這里,我無法弄清楚如何設置input_tensor的數據。 我想將張量設置為類似{{{。0,.1,.2,.3,.4,.5,.6,.7,.8,.9}}}的內容。
我有一個類似的問題,並試圖在C ++中為使用Python訓練的模型設置張量輸入值。 該模型是一個簡單的NN,具有一個隱藏層,用於學習計算XOR運算。
我首先按照這個好帖子的步驟1-4創建了一個包含圖形結構和模型參數的輸出圖形文件: https : //medium.com/@hamedmp/exporting-trained-tensorflow-models-to-c- the-right-way-cf24b609d183#.j4l51ptvb 。
然后在C ++(TensorFlow iOS簡單示例)中,我使用了以下代碼:
tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({4,2}));
// input_tensor_mapped is an interface to the data of a tensor and used to copy data into the tensor
auto input_tensor_mapped = input_tensor.tensor<float, 2>();
// set the (4,2) possible input values for XOR
input_tensor_mapped(0, 0) = 0.0;
input_tensor_mapped(0, 1) = 0.0;
input_tensor_mapped(1, 0) = 0.0;
input_tensor_mapped(1, 1) = 1.0;
input_tensor_mapped(2, 0) = 1.0;
input_tensor_mapped(2, 1) = 0.0;
input_tensor_mapped(3, 0) = 1.0;
input_tensor_mapped(3, 1) = 1.0;
tensorflow::Status run_status = session->Run({{input_layer, input_tensor}},
{output_layer}, {}, &outputs);
在此之后, GetTopN(output->flat<float>(), kNumResults, kThreshold, &top_results);
返回相同的4個值(0.94433498,0.94425952,0.06565627,0.05823805),就像我在訓練模型后的XOR測試代碼中一樣,在top_results中。
因此,如果張量的形狀為{1,1,10},則可以按如下方式設置值:
auto input_tensor_mapped = input_tensor.tensor<float, 3>();
input_tensor_mapped(0, 0, 0) = 0.0;
input_tensor_mapped(0, 0, 1) = 0.1;
....
input_tensor_mapped(0, 0, 9) = 0.9;
Credit: 如何將OpenCV Mat傳遞給C ++ Tensorflow圖表? 非常有幫助。
如果要直接設置張量的值,可以使用Tensor接口提供的少量實用程序功能。 對於最常見的線性訪問,您可以使用flat<T>
。
void ExpectClose(const Tensor& x, const Tensor& y, double atol, double rtol) {
auto Tx = x.flat<T>();
auto Ty = y.flat<T>();
for (int i = 0; i < Tx.size(); ++i) {
if (!IsClose(Tx(i), Ty(i), atol, rtol)) {
LOG(ERROR) << "x = " << x.DebugString();
LOG(ERROR) << "y = " << y.DebugString();
LOG(ERROR) << "atol = " << atol << " rtol = " << rtol
<< " tol = " << atol + rtol * std::fabs(Tx(i));
EXPECT_TRUE(false) << i << "-th element is not close " << Tx(i) << " vs. "
<< Ty(i);
}
}
}
要創建張量,您可以使用其中一個構造函數
Tensor(DT_FLOAT, new TensorShape(..))
如果要在運行時設置張量或占位符的值,則需要通過Run()
接口傳遞它:
Status run_status = session->Run({{input_layer, resized_tensor}},
{output_layer}, {}, &outputs);
if (!run_status.ok()) {
LOG(ERROR) << "Running model failed: " << run_status;
return -1;
}
如果要使用張量的預定義值,可以使用Const構造函數
tensorflow::ops::Const({input_height, input_width})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.