tf.keras.layers.Reshape

Rescale input tensors to specific dimensions

keras.layers.Reshape(target_shape)

target_shape is the target size. A tuple of integers. Axes representing batches are not included.

That is, Reshape will not change the dimension representing the batch.


example

from tensorflow.keras.layers import Reshape
import tensorflow as tf
import numpy as np

# 生成一个维度为[64, 12]的矩阵
x = np.random.random((64, 12))
print(x.shape)

# 转成tensor类型,第一个维度64表示batch
# numpy中的数据类型和tensorflow中的数据类型完全兼容,所以这一步可以省略
x = tf.convert_to_tensor(x)
print(x.shape) # [64, 12]

# 定义一个Reshape层,将输入张量尺寸调整为[3, 4],batch依然是64
reshape1 = Reshape((3, 4))
y1 = reshape1(x)
print(y1.shape) # [64, 3, 4]

# 定义一个Reshape层,将输入张量尺寸调整为[2, 6],batch依然是64
reshape2 = Reshape((2, 6))
y2 = reshape2(x)
print(y2.shape) # [64, 2, 6]

# 定义一个Reshape层,将输入张量尺寸调整为[-1, 2, 6],-1表示此维度大小个根据其他维度推算,batch依然是64
reshape3 = Reshape((-1, 2, 6))
y3 = reshape3(x)
print(y3.shape) # [64, 1, 2, 6]

Guess you like

Origin blog.csdn.net/weixin_46566663/article/details/127620777