tf.reshape源码解析:
功能:重置向量的大小
使用:shape中的-1表示为默认填充值,在满足其他维度的前提下,剩下的值大小
源码解析如下:
def reshape(tensor, shape, name=None):
r"""Reshapes a tensor.
Given `tensor`, this operation returns a tensor that has the same values
as `tensor` with shape `shape`.
If one component of `shape` is the special value -1, the size of that dimension
is computed so that the total size remains constant. In particular, a `shape`
of `[-1]` flattens into 1-D. At most one component of `shape` can be -1.
If `shape` is 1-D or higher, then the operation returns a tensor with shape
`shape` filled with the values of `tensor`. In this case, the number of elements
implied by `shape` must be the same as the number of elements in `tensor`.
For example:
# tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]
# tensor 't' has shape [9] 向量共9个元素
reshape(t, [3, 3]) ==> [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]] # 重置为3x3
# tensor 't' is [[[1, 1], [2, 2]],
# [[3, 3], [4, 4]]]
# tensor 't' has shape [2, 2, 2] 向量大小为[2,2,2],共8个元素
reshape(t, [2, 4]) ==> [[1, 1, 2, 2],
[3, 3, 4, 4]] # 重置为2x4
# 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] 共 3x2x3=18个元素
# pass '[-1]' to flatten 't' 其中的-1相当于默认,这一维度的值自动填充,此处变更为1维。默认填充为18
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: -1默认为填充9
reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]] # 共18个元素,重置为二维,其中一维大小为2,另一维大小为 18/2=9,所以-1代替9
# -1 is inferred to be 2: -1默认代替2
reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]] # 共18个元素,重置为二维,其中一维大小为9,另一维大小为 18/9=2,所以-1代替2
# -1 is inferred to be 3: -1代替3
reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1],
[2, 2, 2],
[3, 3, 3]],
[[4, 4, 4],
[5, 5, 5],
[6, 6, 6]]] # 共18个元素,重置为三维,其中一维大小为2,另一维大小为3,最后一维的大小为: 18/3/2=3,所以-1代替3
# tensor 't' is [7]
# shape `[]` reshapes to a scalar 空也表示为默认填充值
reshape(t, []) ==> 7