在Keras中正确保存迁移学习模型的方法

我使用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')

我使用了相同的方法,这运作得非常好。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注