在数学上,张量是一种几何实体,广义上表示任意形式的数据,可以理解为0阶标量、1阶向量、2阶矩阵在高维空间上的推广,张量的阶描述了它所表示数据的最大维度。
阶数 | 数据实体 | Python样例 |
---|---|---|
0 | 标量 | scalar=1 |
1 | 向量 | vector=[1,2,3] |
2 | 矩阵 | matrix=[[1,2,3],[4,5,6],[7,8,9]] |
3 | 数据立方 | tensor=[[[1],[2],[3]],[[4],[5],[6]],[[7],[8],[9]],…] |
n | n阶张量 | … |
在TensorFlow中,张量(Tensor)表示的是某种相同类型的多维数组。
张量的两个属性:(1)数据类型(浮点型、整型、字符串、复数等);(2)数组的形状(各个维度的大小)。
注意:
(1)张量是用来表示多维数据的;
(2)张量是执行操作时的输入或输出数据;
(3)用户通过执行操作来创建或计算张量;
(4)张量的形状不一定在编译时确定,可以在运行时通过形状推断计算得出。
几个比较常见的张量由以下几个操作产生:
tf.constant #常量(值不可改变)
tf.placeholder #占位符(描述数据的外壳,相当于盛数据的容器)
tf.Variable #变量(会存在内存中)
利用Spyder实践一下,体验一下张量究竟为何物!!!!
例1:0阶张量
mammal=tf.Variable("Elephant",tf.string)
ignition=tf.Variable(451,tf.int16)
floating=tf.Variable(3.1415926,tf.float64)
its_complicated=tf.Variable(12.3-4.85j,tf.complex64)
在控制台上输入下面这句话
[mammal, ignition, floating, its_complicated]
得到如下结果:
其中:tf.Variable是返回的类型,Variable_8:0是在内存中的名字,shape是形状,dtype是数据类型
例2:1阶张量
mystr=tf.Variable(["hello","world"],tf.string)
cool_numbers=tf.Variable([3.14,1.414],tf.float32)
first_primes=tf.Variable([2,3,5,7,11],tf.int32)
its_very_complicated=tf.Variable([12.3-4.85j,.5+1.2j],tf.complex64)
同理:可以看到shape发生了变化
例3:2阶张量(注意:相对于1阶,有2层[ ])
mymat = tf.Variable([[7],[1]], tf.int16)
myxor = tf.Variable([[False, True],[True, False]], tf.bool)
linear_squares = tf.Variable([[4], [9], [16], [25]], tf.int32)
squarish_squares = tf.Variable([ [4, 9], [16, 25] ], tf.int32)
rank_of_squares = tf.rank(squarish_squares)
mymatC = tf.Variable([[7],[11]], tf.int32)
比如(4,1)可以这样理解,在1阶上是4维,2阶上是1维。
例4:3阶张量
linear_squares = tf.Variable([[[2,1], [4,1], [6,1]], [[8,1], [10,1], [12,1]]], tf.int32)
例5:4阶张量
my_image = tf.zeros([10, 299, 299, 3])
一个比较有趣的例子(RGB彩色图片)可以参照https://www.cnblogs.com/xiaoboge/p/9681229.html,加深一下理解。