是否可以在tf.keras.applications中删除/替换预训练的ResNet50模型的BOTTOM层?
例如,我尝试这样做:
import tensorflow as tf
pretrained_resnet = tf.keras.applications.ResNet50(include_top=False, weights='imagenet')
inputs = tf.keras.Input(shape=(256,256,1))
x = tf.keras.layers.ZeroPadding2D()(inputs)
x = tf.keras.layers.Conv2D(filters=64,
kernel_size=(7,7),
strides=(2,2),
padding='same')(x)
outputs = pretrained_resnet.layers[3](x)
test = tf.keras.Model(inputs, pretrained_resnet.output)
但是它给出了这个错误:ValueError:图形断开:无法获得张量Tensor(“ input_2:0”,.......
我也尝试过使用tf.keras顺序API,但是由于ResNet不是顺序模型,因此无法使用。我基本上只是想用一个新的替换ResNet50中的第一个Conv2D层。这可能吗?还是我必须重写整个ResNet模型?
任何建议将不胜感激!
答案 0 :(得分:2)
ZeroPadding2D
和Conv2D (7*7, 64, stride 2)
是2nd
网络的3rd
和Resnet50
层。
因此,此处显示仅替换Resnet50
的第一层(即输入层)
from tensorflow.keras.applications import ResNet50
import tensorflow as tf
model = ResNet50(include_top = False, weights = 'imagenet')
model.save('model.h5')
res50_model = tf.keras.models.load_model('model.h5')
#res50_model.summary()
要从网络中删除第一层,您可以运行以下代码
res50_model._layers.pop(0)
Resnet50 expects the input must have 3 channels
,因此将输入图层形状添加为(256,256,3)
而不是(256,256,1)
。
要添加新的输入层,可以运行以下代码
newInput = tf.keras.Input(shape=(256,256,3))
newOutputs = res50_model(newInput)
newModel = tf.keras.Model(newInput, newOutputs)
newModel.summary()
输出:
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_2 (InputLayer) [(None, 256, 256, 3)] 0
_________________________________________________________________
resnet50 (Model) multiple 23587712
=================================================================
Total params: 23,587,712
Trainable params: 23,534,592
Non-trainable params: 53,120
_________________________________________________________________