TensorFlow:使用tf.reshape函数重塑张量

2018-12-25 11:01 更新

TensorFlow - tf.reshape 函数

reshape(
    tensor,
    shape,
    name=None
)

参见指南:张量变换>形状和形状

重塑张量.

给定tensor,这个操作返回一个张量,它与带有形状shape的tensor具有相同的值.

如果shape的一个分量是特殊值-1,则计算该维度的大小,以使总大小保持不变.特别地情况为,一个[-1]维的shape变平成1维.至多能有一个shape的分量可以是-1.

如果shape是1-D或更高,则操作返回形状为shape的张量,其填充为tensor的值.在这种情况下,隐含的shape元素数量必须与tensor元素数量相同.

例如:

# 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

参数:

  • tensor:一个Tensor.
  • shape:一个Tensor;必须是以下类型之一:int32,int64;用于定义输出张量的形状.
  • name:操作的名称(可选).

返回值:

该操作返回一个Tensor.与tensor具有相同的类型.

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号