1. 张量(tensor)
定义张量:
全1:
a = tf.ones((2,2), dtype = tf.int16, name = 'a')
# 输出:
# <tf.Tensor 'a:0' shape=(2, 2) dtype=int16>
除了维度,dtype, name 可选,空时,dtype 为tf.float32
。
常量:
a = tf.constant(1, shape = (2,3))
# 输出:
# <tf.Tensor 'Const_1:0' shape=(2, 3) dtype=int32>
全0:
a = tf.zeros((3,3))
# 输出:
# <tf.Tensor 'zeros_1:0' shape=(3, 3) dtype=float32>
定义变量:
tf.Variable:
a = tf.Variable(initial_value = 1, trainable = True)
# 输出:
# <tf.Variable 'Variable:0' shape=() dtype=int32_ref>
a = tf.ones((2,2))
# 输出:
# <tf.Tensor 'ones_4:0' shape=(2, 2) dtype=float32>
运算操作:
加法:
>>> result = tf.add(a,b,name='addTwo')
>>> print(result)
Tensor("addTwo:0", shape=(2,), dtype=float32)
注:shape(2,)
是一个一维数组,长度为2。
张量,有三个属性,分别为:名称addTwo,维度shape,类型type。
张量本身并没有存储具体的数值,需要会话session来计算。
2. tensor支持的类型
tensor,支持14种不同类型,分别为
实数
(tf.float32, tf.float64),
整数
(tf.int8, tf.int16, tf.int32,tf.int64, tf.unit8),
布尔型
(tf.bool),
复数
(tf.complex64, tf.complex128).