导语
在深度学习中,数据变形非常普遍,reshape作用是将tensor变换为参数shape的形式
语法
tf.reshape(tensor, shape, name=None)
tensor为入参,shape为变换的矩阵格式,name可略
实例1
import tensorflow as tf
#定义常量,一维矩阵
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7,8])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) #初始化Tensor变量
print(sess.run(tensor)) #输出常量
#转换为两行四列的矩阵,shape=[2,4]
tensorReshape = tf.reshape(tensor,[2,4])
print(sess.run(tensorReshape)) #输出变形后
第一个print原矩阵
[1 2 3 4 5 6 7 8]
第二个print输出变换的矩阵
[[1 2 3 4]
[5 6 7 8]]
shape的列表数决定了转换后的矩阵维度,比如
shape=[2,4]#二维矩阵
shape=[1,2,4]#三维矩阵
shape的列表值可以为-1
实例2
import tensorflow as tf
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7,8])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
tensorReshape = tf.reshape(tensor,[2,-1])
print(sess.run(tensorReshape))
输出
[[1 2 3 4]
[5 6 7 8]]
实例3
import tensorflow as tf
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7,8])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
tensorReshape = tf.reshape(tensor,[-1,4])
print(sess.run(tensorReshape))
输出
[[1 2 3 4]
[5 6 7 8]]
可以看出shape的三种入参形式[2,4][2,-1][-1,4],得到相同的变换矩阵,
-1代表的含义是不用我们自己指定这一维的大小,函数会自动计算,但列表中只能存在一个-1
附:官方例子
# tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]
# tensor 't' has shape [9]
reshape(t, [3, 3]) ==> [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# tensor 't' is [[[1, 1], [2, 2]],
# [[3, 3], [4, 4]]]
# tensor 't' has shape [2, 2, 2]
reshape(t, [2, 4]) ==> [[1, 1, 2, 2],
[3, 3, 4, 4]]
# tensor 't' is [[[1, 1, 1],
# [2, 2, 2]],
# [[3, 3, 3],
# [4, 4, 4]],
# [[5, 5, 5],
# [6, 6, 6]]]
# tensor 't' has shape [3, 2, 3]
# pass '[-1]' to flatten 't'
reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6]
# -1 can also be used to infer the shape
# -1 is inferred to be 9:
reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]]
# -1 is inferred to be 2:
reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]]
# -1 is inferred to be 3:
reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],
[2, 2, 2],
[3, 3, 3]],
[[4, 4, 4],
[5, 5, 5],
[6, 6, 6]]]
# tensor 't' is [7]
# shape `[]` reshapes to a scalar
reshape(t, []) ==> 7