问题描述
我这样创建一个张量:
tensorflow::Tensor a(tensorflow::DT_FLOAT, tensorflow::TensorShape());
我知道如何填充标量值:
I know how to fill a scalar value:
a.scalar<float>()() = 8.0;
但我不知道如何填充像[1,4,2]的张量。 / p>
But I don't know how to fill a tensor like [1, 4, 2].
推荐答案
有几个选项。如果张量真的是一个小向量,就像你的情况,你可以做以下:
There are a few options. If the tensor is really a small vector, like in your case, you can do the following :
tensorflow::Tensor a(tensorflow::DT_FLOAT, tensorflow::TensorShape(3));
a.vec<float>()(0) = 1.0f;
a.vec<float>()(1) = 4.0f;
a.vec<float>()(2) = 2.0f;
如果要构造稍大和/或多维张量,在 tensorflow / cc / framework / ops.h
中声明的c> tensorflow :: ops :: Input :: Initializer 有许多构造函数, a Tensor
来自各种C ++常量,例如简单的基本常量和表示多维数组的嵌套初始化列表。
If you want to construct a slightly larger and/or multi-dimensional tensor, then tensorflow::ops::Input::Initializer
declared in tensorflow/cc/framework/ops.h
has many constructors that lets you construct a Tensor
from various kinds of C++ constants such as simple primitive constants and nested initializer lists representing a multi-dimensional array.
例如,如果您想构造一个 2x2
矩阵,您可以执行以下操作:
For example, if you want to construct a 2x2
matrix, you can do the following :
#include "tensorflow/cc/framework/cc/ops.h"
tensorflow::ops::Input::Initializer a({{1, 2}, {3, 4}});
// a.tensor will be a Tensor with type DT_INT32 and shape {2, 2}.
这篇关于如何在C ++中填充张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!