我使用ResNet50在Keras中通过迁移学习训练了一个宪法网络,如下所示。
base_model = applications.ResNet50(weights='imagenet', include_top=False, input_shape=(333, 333, 3))## set model architechturex = base_model.outputx = GlobalAveragePooling2D()(x)x = Dense(1024, activation='relu')(x) x = Dense(256, activation='relu')(x) predictions = Dense(y_train.shape[1], activation='softmax')(x) model = Model(input=base_model.input, output=predictions)model.compile(loss='categorical_crossentropy', optimizer=optimizers.SGD(lr=1e-4, momentum=0.9), metrics=['accuracy'])model.summary()
在按如下方式训练模型后,我希望保存该模型。
history = model.fit_generator( train_datagen.flow(x_train, y_train, batch_size=batch_size), steps_per_epoch=600, epochs=epochs, callbacks=callbacks_list)
由于模型类型为Model,我无法使用Keras的models中的save_model()函数。我使用save()函数来保存模型。但后来当我加载模型并验证时,模型表现得像是未经训练的模型。我认为权重没有被保存。问题出在哪里?如何正确保存这个模型?
回答:
根据Keras官方文档,如果你只需要保存模型的架构,可以使用
model_json = model.to_json()with open("model_arch.json", "w") as json_file: json_file.write(model_json)
要保存权重
model.save_weights("my_model_weights.h5")
你可以稍后加载json文件并使用
from keras.models import model_from_jsonmodel = model_from_json(json_string)
同样,对于权重,你可以使用
model.load_weights('my_model_weights.h5')
我使用了相同的方法,这运作得非常好。