tf.reshape(tensor, shape, name=None)
的作用是将tensor
变换为参数shape
的形式。其中shape
为一个列表形式,特殊的一点是列表中可以存在-1
,-1
代表的含义是不用我们自己指定这一维的大小,函数会自动计算,但列表中只能存在一个-1
(当然如果存在多个-1
,就是一个存在多解的方程了)。
TensorFlow
根据shape
变换矩阵的方式为reshape(t, shape) => reshape(t, [-1]) => reshape(t, shape)
,首先将矩阵t
变为一维矩阵,然后再对矩阵的形式进行更改。
# 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
reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3], # -1 is inferred to be 9
[4, 4, 4, 5, 5, 5, 6, 6, 6]]
reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3], # -1 is inferred to be 2
[4, 4, 4, 5, 5, 5, 6, 6, 6]]
reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1], # -1 is inferred to be 3
[2, 2, 2],
[3, 3, 3]],
[[4, 4, 4],
[5, 5, 5],
[6, 6, 6]]]
reshape(t, []) ==> 7 # tensor 't' is [7]. shape `[]` reshapes to a scalar