assert os.path.exists(weights_path), 'Model weights not found (see "weights_path" variable in script).'
f = h5py.File(weights_path)
for k in range(f.attrs['nb_layers']):if k >= len(model.layers):# we don't look at the last (fully-connected) layers in the savefilebreakg = f['layer_{}'.format(k)]weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]model.layers[k].set_weights(weights)
f.close()
print('Model loaded.')
然后在VGG16結構基礎上添加一個簡單的分類器及預訓練好的模型:
top_model = Sequential()
top_model.add(Flatten(input_shape=model.output_shape[1:]))
top_model.add(Dense(256, activation='relu'))
top_model.add(Dropout(0.5))
top_model.add(Dense(1, activation='sigmoid'))
top_model.load_weights(top_model_weights_path)
# add the model on top of the convolutional base
model.add(top_model)
把隨后一個卷積塊前的權重設置為不訓練:
for layer in model.layers[:25]:layer.trainable = False
model.compile(loss='binary_crossentropy',optimizer=optimizers.SGD(lr=1e-4, momentum=0.9),metrics=['accuracy'])