Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a tensor in C++

Tags:

c++

tensorflow

I'm creating a tensor like this:

tensorflow::Tensor a(tensorflow::DT_FLOAT, tensorflow::TensorShape());

I know how to fill a scalar value:

a.scalar<float>()() = 8.0;

But I don't know how to fill a tensor like [1, 4, 2].

like image 780
Kevin Avatar asked Aug 25 '16 15:08

Kevin


2 Answers

tensorflow::Input::Initializer a({{1, 2}, {3, 4}});

Actually it works in compiling, but errors when running, which shows that a is a tensor with [0] tensorshape. I don't know where is wrong, but my successful way is:

tensorflow::Input::Initializer a({1, 2, 3, 4}, tensorflow::TensorShape({2, 2}));
like image 122
fiverwyp Avatar answered Oct 15 '22 14:10

fiverwyp


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;

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.

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}.
like image 35
keveman Avatar answered Oct 15 '22 16:10

keveman