|
| 1 | +# TensorFlow Tensor |
| 2 | + |
| 3 | +https://www.tensorflow.org/api_docs/cc/class/tensorflow/tensor |
| 4 | + |
| 5 | +## Create a tensor |
| 6 | + |
| 7 | +**Create a vector tensor** |
| 8 | +```cpp |
| 9 | +#include <tensorflow/core/public/session.h> |
| 10 | +#include <tensorflow/core/platform/env.h> |
| 11 | + |
| 12 | +using namespace std; |
| 13 | +using namespace tensorflow; |
| 14 | + |
| 15 | +int main(int argc, char* argv[]) { |
| 16 | + |
| 17 | + Tensor a(DT_FLOAT, TensorShape({2})); |
| 18 | + auto a_vec = a.vec<float>(); |
| 19 | + a_vec(0) = 1.0f; |
| 20 | + a_vec(1) = 2.0f; |
| 21 | + |
| 22 | + cout << "Vector tensor" << endl; |
| 23 | + |
| 24 | + return 0; |
| 25 | +} |
| 26 | +``` |
| 27 | +
|
| 28 | +**Create a matrix tensor** |
| 29 | +```cpp |
| 30 | +#include <tensorflow/core/public/session.h> |
| 31 | +#include <tensorflow/core/platform/env.h> |
| 32 | +
|
| 33 | +using namespace std; |
| 34 | +using namespace tensorflow; |
| 35 | +
|
| 36 | +int main(int argc, char* argv[]) { |
| 37 | +
|
| 38 | + Tensor b(DT_FLOAT, TensorShape({2,2})); |
| 39 | + auto b_mat = b.matrix<float>(); |
| 40 | + b_mat(0,0) = 1.0f; |
| 41 | + b_mat(0,1) = 2.0f; |
| 42 | + b_mat(1,0) = 3.0f; |
| 43 | + b_mat(1,1) = 4.0f; |
| 44 | +
|
| 45 | + return 0; |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +**Print tensor components** |
| 50 | + |
| 51 | +Method 1: |
| 52 | +```cpp |
| 53 | +... |
| 54 | + cout << "First element: " << a_vec(0) << endl; // output: 1 |
| 55 | + // or |
| 56 | + cout << "First element: " << b_mat(0) << endl; // output: 1 |
| 57 | +... |
| 58 | +``` |
| 59 | + |
| 60 | +Method 2: pointer |
| 61 | +```cpp |
| 62 | +... |
| 63 | + // get pointer to memory for the tensor |
| 64 | + float * p = b.vec<float>().data(); |
| 65 | + cout << typeid(p).name() << endl; |
| 66 | + cout << p[0] << endl; |
| 67 | + cout << p[1] << endl; |
| 68 | + cout << p[2] << endl; |
| 69 | + cout << p[3] << endl; |
| 70 | +... |
| 71 | +``` |
| 72 | + |
| 73 | +**Print shape info** |
| 74 | +```cpp |
| 75 | +... |
| 76 | + cout << b.shape().dims() << endl; |
| 77 | + // output: 2 |
| 78 | +... |
| 79 | +``` |
| 80 | + |
| 81 | +## Convert vector to tensor |
| 82 | + |
| 83 | +**Use `std::copy` |
| 84 | +```cpp |
| 85 | +... |
| 86 | + vector<float> myvec = {5,6,7}; |
| 87 | + Tensor a(DT_FLOAT, TensorShape({3})); |
| 88 | + copy(myvec.begin(), myvec.end(), a.flat<float>().data() ); |
| 89 | +... |
| 90 | +``` |
0 commit comments