Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

most efficient way to create tensorflow::tensor from std::vector

Tags:

c++

tensorflow

So my question is to know if there is a way to pass directly the values from a vector (but we could also think about array) to a tensorflow::tensor?

The only way I know is to copy each value one by one.

Example (2D Vector):

tensorflow::Tensor input(tensorflow::DT_FLOAT, tensorflow::TensorShape({50, 20})); 
auto input_map = input.tensor<float, 2>();


for (int b = 0; b < 50; b++) {
  for (int c = 0; c < 20; c++) {
    input_map(b, c) = (vector_name)[b][c];
  }
}

Is there more convenient ways to do it?

For example array to vector:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
like image 596
rAyyy Avatar asked Sep 28 '16 02:09

rAyyy


People also ask

Is std::vector fast?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.

Should I use std for vector?

If you need a "dynamic" array, then std::vector is the natural solution. It should in general be the default container for everything. But if you want a statically sized array created at time of compilation (like a C-style array is) but wrapped in a nice C++ object then std::array might be a better choice.

How many main types of tensors can you create in TensorFlow?

There are four main tensor type you can create: tf. Variable. tf.

Are TensorFlow tensors immutable?

All tensors are immutable like Python numbers and strings: you can never update the contents of a tensor, only create a new one.


1 Answers

how about this? std::copy_n(vec.begin(), vec.size(), input.flat<float>().data())

like image 186
xsj0jsx Avatar answered Sep 29 '22 13:09

xsj0jsx