我正在使用预先训练的 ResNet 模型,并且正在使用数据集训练模型的几个层,但我希望将 ResNet 的预处理作为模型的一层包含在内。
如何做到这一点?
最佳答案
如果您想使用tf.keras.applications.resnet50.preprocess_input()
,请尝试:
import tensorflow as tf
resnet = tf.keras.applications.ResNet50(
include_top=False ,
weights='imagenet' ,
input_shape=( 256 , 256 , 3) ,
pooling='avg' ,
classes=13
)
for layer in resnet.layers:
layer.trainable = False
model = tf.keras.Sequential()
model.add(tf.keras.layers.Lambda(tf.keras.applications.resnet50.preprocess_input, input_shape=(256, 256, 3)))
model.add(resnet)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(22, activation='softmax',name='output') )
model.compile( loss='mse' , optimizer='adam' )
print(model(tf.random.normal((1, 256, 256, 3))))
tf.Tensor(
[[0.12659772 0.02955576 0.13070999 0.0258545 0.0186768 0.01459627
0.07854564 0.010685 0.01598095 0.04758708 0.05001146 0.20679766
0.00975605 0.01047837 0.00401289 0.01095579 0.06127766 0.0313729
0.00884041 0.04098257 0.01187507 0.05484949]], shape=(1, 22), dtype=float32)
关于deep-learning - 向模型添加预处理层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71401092/