一.张量
TensorFlow 中的 Tensor 表示张量,是多维数组、多维列表的意思,可以用阶来表示张量的维数。
- 标量:0 阶的数值,一个单独的数,如 135。
- 向量:1 阶的数值,一列或一行数组,如 [1, 3, 5]。
- 矩阵:2 阶的数值,二维数组 ,如 [[1, 2, 3], [4, 5, 6]]。
- 张量:超过 2 阶的数值,高维数组,如 [[[xxx]]]。
二.张量的生成
1.constant(常量)
t = tf.constant(value,dtype = None,shape=None,name = 'Const')
# dtype默认为int32/float32,可以指定
# shape自动识别,可以指定
t0 = tf.constant(4) # 0维张量(标量)
t1 = tf.constant([1,2]) # 1维张量
t2 = tf.constant([[1],[2]]) # 2维张量
t3 = tf.constant([[[1]],[[2]]]) # 3维张量
2.Variable(变量,参数可变,形状不可变)
v = tf.Variable(value)
v.assign(newvalue) # 修改v的值,和原shape相同时通过,不相同时报错
3.张量转numpy
t = np.array(tensor)
t = tensor.numpy()
4.常用函数
a = tf.constant([[1,2],[3,4]])
b = tf.constant([[1,2],[3,4]])
tf.add(a,b) # 求和
tf.sub(a,b) # 减法
tf.multiply(a,b) # 点乘
tf.div(a,b) # 除法
tf.mod(a,b) # 取模
tf.abs(a) # 绝对值
tf.matmul(a,b) # 矩阵乘法,注意行与列