如何在Keras上仅加载特定的砝码 [英] How to load only specific weights on Keras
问题描述
我有一个训练有素的模型,我已经导出了权重,并希望部分加载到另一个模型中. 我的模型是使用TensorFlow作为后端在Keras中构建的.
I have a trained model that I've exported the weights and want to partially load into another model. My model is built in Keras using TensorFlow as backend.
现在我正在执行以下操作:
Right now I'm doing as follows:
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape, trainable=False))
model.add(Activation('relu', trainable=False))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3), trainable=False))
model.add(Activation('relu', trainable=False))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), trainable=True))
model.add(Activation('relu', trainable=True))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.load_weights("image_500.h5")
model.pop()
model.pop()
model.pop()
model.pop()
model.pop()
model.pop()
model.add(Conv2D(1, (6, 6),strides=(1, 1), trainable=True))
model.add(Activation('relu', trainable=True))
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
我相信这是一种糟糕的方法,尽管它可以工作.
I'm sure it's a terrible way to do it, although it works.
如何仅加载前9层?
推荐答案
如果在最初训练的模型和新模型之间一致地命名了前9层,则可以将model.load_weights()
与by_name=True
结合使用.这样只会在新模型的图层中更新权重,这些图层在原始训练模型中具有相同名称的图层.
If your first 9 layers are consistently named between your original trained model and the new model, then you can use model.load_weights()
with by_name=True
. This will update weights only in the layers of your new model that have an identically named layer found in the original trained model.
可以使用name
关键字指定图层名称,例如:
The name of the layer can be specified with the name
keyword, for example:
model.add(Dense(8, activation='relu',name='dens_1'))
这篇关于如何在Keras上仅加载特定的砝码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!