ags*_*lid 5 c++ machine-learning tensorflow
我正试图通过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);
Run Code Online (Sandbox Code Playgroud)
在此之后,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;
Run Code Online (Sandbox Code Playgroud)
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
要创建张量,您可以使用构造函数之一
Tensor(DT_FLOAT, new TensorShape(..))
Run Code Online (Sandbox Code Playgroud)
如果要在运行时设置张量或占位符的值,则需要通过接口传递它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;
}
Run Code Online (Sandbox Code Playgroud)
如果你想要一个张量的预定义值,你可以使用 Const 构造函数
tensorflow::ops::Const({input_height, input_width})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4237 次 |
最近记录: |