这个问题与这个问题有关:从 Python 导出 Tensorflow 图以在 C++ 中使用
This question is related to this one: Export Tensorflow graphs from Python for use in 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()
方法是 Python tf.Session.run()
方法,它支持使用 <代码>输入参数.就像 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...).
inputs
参数的类型为 const std::vector
.让我们分解一下:
The inputs
argument has type const std::vector<std::pair<string, Tensor>>&
. Let's break this down:
inputs
的每个元素都对应一个您想要在 Run()
调用中提供的张量(例如占位符).元素的类型为 std::pair
.
Each element of inputs
corresponds to a single tensor (such as a placeholder) that you want to feed in the Run()
call. An element has type std::pair<string, Tensor>
.
std::pair
的第一个元素是图中您要提供的张量的名称.例如,假设您使用 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
的值,在这种情况下将是 "placeholder: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
的第二个元素是您想要提供的值,作为 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!