tf.compat.v1.manip.reshape
Переформировывает тензор.
tf.compat.v1.manip.reshape(
tensor, shape, name=None
)
Учитывая tensor, эта операция возвращает новый tf.Tensor, содержащий те же значения, что и tensor в том же порядке, но с новой формой, заданной shape.
t1 = [[1, 2, 3],
[4, 5, 6]]
print(tf.shape(t1).numpy())
[2 3]
t2 = tf.reshape(t1, [6])
t2
<tf.Tensor: shape=(6,), dtype=int32,
numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>
tf.reshape(t2, [3, 2])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4],
[5, 6]], dtype=int32)>Операция tf.reshape не изменяет порядок и общее количество элементов в тензоре, поэтому она может повторно использовать буфер данных. Это делает её быстрой операцией, независимо от размера обрабатываемого тензора.
tf.reshape([1, 2, 3], [2, 2]) Traceback (most recent call last): InvalidArgumentError: Input to reshape is a tensor with 3 values, but the requested shape has 4
Чтобы вместо этого переупорядочить данные для изменения размерностей тензора, см. tf.transpose.
t = [[1, 2, 3],
[4, 5, 6]]
tf.reshape(t, [3, 2]).numpy()
array([[1, 2],
[3, 4],
[5, 6]], dtype=int32)
tf.transpose(t, perm=[1, 0]).numpy()
array([[1, 4],
[2, 5],
[3, 6]], dtype=int32)Если один компонент shape имеет специальное значение -1, размер этого измерения вычисляется таким образом, чтобы общее количество элементов оставалось постоянным. В частности, shape из [-1] сжимается в 1-мерный тензор. Максимально один компонент shape может быть -1.
t = [[1, 2, 3],
[4, 5, 6]]
tf.reshape(t, [-1])
<tf.Tensor: shape=(6,), dtype=int32,
numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>
tf.reshape(t, [3, -1])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4],
[5, 6]], dtype=int32)>
tf.reshape(t, [-1, 2])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 2],
[3, 4],
[5, 6]], dtype=int32)>tf.reshape(t, []) переформировывает тензор t с одним элементом в скаляр.
tf.reshape([7], []).numpy() 7
Дополнительные примеры:
t = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(tf.shape(t).numpy())
[9]
tf.reshape(t, [3, 3])
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=int32)>t = [[[1, 1], [2, 2]],
[[3, 3], [4, 4]]]
print(tf.shape(t).numpy())
[2 2 2]
tf.reshape(t, [2, 4])
<tf.Tensor: shape=(2, 4), dtype=int32, numpy=
array([[1, 1, 2, 2],
[3, 3, 4, 4]], dtype=int32)>t = [[[1, 1, 1],
[2, 2, 2]],
[[3, 3, 3],
[4, 4, 4]],
[[5, 5, 5],
[6, 6, 6]]]
print(tf.shape(t).numpy())
[3 2 3]
# Pass '[-1]' to flatten 't'.
tf.reshape(t, [-1])
<tf.Tensor: shape=(18,), dtype=int32,
numpy=array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],
dtype=int32)>
# -- Using -1 to infer the shape --
# Here -1 is inferred to be 9:
tf.reshape(t, [2, -1])
<tf.Tensor: shape=(2, 9), dtype=int32, numpy=
array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]], dtype=int32)>
# -1 is inferred to be 2:
tf.reshape(t, [-1, 9])
<tf.Tensor: shape=(2, 9), dtype=int32, numpy=
array([[1, 1, 1, 2, 2, 2, 3, 3, 3],
[4, 4, 4, 5, 5, 5, 6, 6, 6]], dtype=int32)>
# -1 is inferred to be 3:
tf.reshape(t, [ 2, -1, 3])
<tf.Tensor: shape=(2, 3, 3), dtype=int32, numpy=
array([[[1, 1, 1],
[2, 2, 2],
[3, 3, 3]],
[[4, 4, 4],
[5, 5, 5],
[6, 6, 6]]], dtype=int32)>| Args | |
|---|---|
tensor | A Tensor. |
shape | A Tensor. Должен быть одного из следующих типов: int32, int64. Определяет форму выходного тензора. |
name | Необязательная строка. Имя операции. |
| Returns | |
|---|---|
A Tensor. Имеет тот же тип, что и tensor. |
© 2022 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 4.0.
Code samples licensed under the Apache 2.0 License.
https://www.tensorflow.org/api_docs/python/tf/compat/v1/manip/reshape