tf.keras.layers.Reshape

将输入张量重新调整为特定的尺寸

keras.layers.Reshape(target_shape)

target_shape为目标尺寸。整数元组。 不包含表示批量的轴。

即Reshape不会改变表示batch的维度。


示例

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]

猜你喜欢

转载自blog.csdn.net/weixin_46566663/article/details/127620777