# TensorFlow - Tensor理解与使用

TensorFlow - Tensor理解与使用

flyfish

tensor 张量

What is a Tensor?

Tensors are simply mathematical objects that can be used to describe
physical properties, just like scalars and vectors. In fact tensors
are merely a generalisation of scalars and vectors; a scalar is a zero
rank tensor, and a vector is a first rank tensor.

The rank (or order) of a tensor is defined by the number of directions
(and hence the dimensionality of the array) required to describe it.
For example, properties that require one direction (first rank) can be
fully described by a 3×1 column vector, and properties that require
two directions (second rank tensors), can be described by 9 numbers,
as a 3×3 matrix. As such, in general an nth rank tensor can be
described by 3n coefficients.

import tensorflow as tf
a=tf.constant([1.0,2.0],name='a')
b=tf.constant([2.0,3.0],name='b')

 #使用张量记录中间结果
a=tf.constant([1.0,2.0],name='a')
b=tf.constant([2.0,3.0],name='b')
result=a+b

#直接结计算向量的和，可能性差
result=tf.constant([1.0,2.0],name='a')+ tf.constant([2.0,3.0],name='b')

2当计算图构造完成之后，张量可以来获得计算结果，也就是得到真实的数字。虽然张量本身没有存储具体的数字，但可以通过会话session得到这些具体的数字。

C++使用 Tensor的一些示例
class Tensor的源码目录是
\tensorflow\core\framework\tensor.h
python里边的tensor是numpy ndarry，C++里面使用了第三方库Eigen库的封装-class Tensor

eigen\unsupported\Eigen\CXX11\src\Tensor

Eigen库的unsupported部分没有官方支持。
CHECK fails表示在编译时就已经发现了错误

typedef float T;
Tensor T1(DT_FLOAT, TensorShape({}));

Tensor my_mat(DT_FLOAT, TensorShape({ 3, 5 }));
// built with Shape{rows: 3, cols: 5}

auto mat1 = my_mat.matrix<T>();    // 2D Eigen::Tensor, 3 x 5.
auto mat2 = my_mat.tensor<T, 2>(); // 2D Eigen::Tensor, 3 x 5.
//auto mat3 = my_mat.matrix<int32>();// CHECK fails as type mismatch.
//auto vec1 = my_mat.vec<T>();       // CHECK fails as my_mat is 2D.
//auto vec2 = my_mat.tensor<T, 3>(); // CHECK fails as my_mat is 2D.

// Tensor my_ten(...built with Shape{planes: 4, rows: 3, cols: 5}...)
Tensor my_ten(DT_FLOAT, TensorShape({4, 3, 5}));

// 1D Eigen::Tensor, size 60:
auto flat = my_ten.flat<T>();

// 2D Eigen::Tensor 12 x 5:
auto inner = my_ten.flat_inner_dims<T>();

// 2D Eigen::Tensor 4 x 15:
auto outer1 = my_ten.shaped<T, 2>({ 4, 15 });

//// CHECK fails, bad num elements:
//auto outer2 = my_ten.shaped<T, 2>({ 4, 8 });

// 3D Eigen::Tensor 6 x 5 x 2:
auto weird = my_ten.shaped<T, 3>({ 6, 5, 2 });

//// CHECK fails, type mismatch:
//auto bad = my_ten.flat<int32>();

举报原因： 您举报文章：TensorFlow - Tensor理解与使用 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)