在C ++中为Tensorflow模型定义feed_dict [英] Define a feed_dict in c++ for Tensorflow models
问题描述
这个问题与此相关:
从Python导出Tensorflow图以用于C ++
我正在尝试将Tensorflow模型从Python导出到C ++。问题是,我的神经网络从占位符开始以接收输入,这需要feed_dict。我找不到任何c ++ API为模型提供feed_dict。我该怎么办?
I'm trying to export a Tensorflow model from Python to C++. The problem is, my neural net starts with a placeholder to receive input, which requires a feed_dict. I cannot find any c++ API to supply a feed_dict for my model. What can I do?
如果没有提供feed_dicts的API,我应该如何更改我的模型,以便可以在没有占位符的情况下对它进行训练和导出以用于c ++?
If there's no API for supplying feed_dicts, how should I change my model so that it can be trained and exported for c++ purposes without placeholders?
推荐答案
tensorflow :: Session :: Run()
方法在C ++中与Python tf.Session.run()
方法,它支持使用 inputs
参数输入张量。就像C ++和Python中的许多东西一样,它使用起来有点棘手(在这种情况下,文档看起来有点穷...)。
The tensorflow::Session::Run()
method is the C++ equivalent of the Python tf.Session.run()
method, and it supports feeding tensors using the inputs
argument. Like so many things in C++ versus Python, it's just a little more tricky to use (and in this case it looks like the documentation is a bit poorer...).
输入
参数的类型为 const std :: vector< std :: pair< string,Tensor>& 。让我们来分解一下:
The inputs
argument has type const std::vector<std::pair<string, Tensor>>&
. Let's break this down:
-
每个
输入元素
对应一个您想要在Run()
调用中提供的单个张量(例如占位符)。元素的类型为std :: pair< string,Tensor>
。
Each element of
inputs
corresponds to a single tensor (such as a placeholder) that you want to feed in theRun()
call. An element has typestd::pair<string, Tensor>
.
std :: pair< string,Tensor>
是要馈送的图中张量的名称。例如,假设在Python中您拥有:
The first element of the std::pair<string, Tensor>
is the name of the tensor in the graph that you want to feed. For example, let's say in Python you had:
p = tf.placeholder(..., name="placeholder")
# ...
sess.run(..., feed_dict={p: ...})
...然后在C ++中,该对的第一个元素将是 p.name
的值,在这种情况下为占位符:0
...then in C++ the first element of the pair would be the value of p.name
, which in this case would be "placeholder:0"
std :: pair<的第二个元素; string,Tensor>
是您想要提供的值,作为 tensorflow :: Tensor
对象。您必须使用C ++自己构建它,定义一个Numpy数组或Python对象要复杂一些,但这是一个如何指定2 x 2矩阵的示例:
The second element of the std::pair<string, Tensor>
is the value that you want to feed, as a tensorflow::Tensor
object. You have to build this yourself in C++, and it's a bit more complicated that defining a Numpy array or a Python object, but here's an example of how to specify a 2 x 2 matrix:
using tensorflow::Tensor;
using tensorflow::TensorShape;
Tensor t(DT_FLOAT, TensorShape({2, 2}));
auto t_matrix = t.matrix<float>();
t_matrix(0, 0) = 1.0;
t_matrix(0, 1) = 0.0;
t_matrix(1, 0) = 0.0;
t_matrix(1, 1) = 1.0;
...然后可以通过 t
作为配对中的第二个元素。
...and you can then pass t
as the second element of the pair.
这篇关于在C ++中为Tensorflow模型定义feed_dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!