tf.reshape()

2022-09-04 21:34:35 浏览数 (3)

TensorFlow - tf.reshape 函数

代码语言:javascript复制
reshape(
    tensor,
    shape,
    name=None
)

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

参数:

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

返回值:

  • 该操作返回一个张量,与tensor具有相同的类型.

如果shape的一个分量是特殊值-1,则计算该维度的大小,以使总大小保持不变。特别地情况为,一个[-1]维的shape变平成1维。至多能有一个shape的分量可以是-1。如果shape是1-D或更高,则操作返回形状为shape的张量,其填充为tensor的值。在这种情况下,隐含的shape元素数量必须与tensor元素数量相同。

例如:

代码语言:javascript复制
# 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

0 人点赞