# 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 数学运算和逻辑运算

2017-11-09 14:59:45

#### 学习TensorFlow，打印输出tensor的值

2016-06-24 15:01:57

#### TensorFlow入门：第一个机器学习Demo

2017-12-13 20:10:23

#### 对Tensorflow中tensor的理解

2017-04-30 22:19:15

#### tensorflow笔记：流程，概念和简单代码注释

2016-09-27 08:13:18

#### 怎样理解TensorFlow中的Tensor？

2017-07-04 20:49:28

#### tensorflow入门（三）---tensorflow的计算图和tensor

2016-12-15 17:13:10

#### tensorflow+入门笔记︱基本张量tensor理解与tensorflow运行结构

2017-01-22 11:57:34

#### 罗斯基白话：TensorFlow+实战系列（一）之详解Tensor与Flow

2017-04-11 19:36:43

#### 深度学习框架Tensorflow学习与应用

2018-02-22 10:57:51