且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Keras中保存模型的正确方法

更新时间:2022-01-10 07:46:27

Keras支持一个更简单的界面,可将模型权重和模型体系结构一起保存到单个H5文件中。

Keras supports a simpler interface to save both the model weights and model architecture together into a single H5 file.

使用save.model方法保存模型包括我们需要了解的有关模型的所有信息,包括:

Saving the model with save.model way includes everything we need to know about the model, including:


  1. 模型权重。

  2. 模型体系结构。

  3. 模型编译详细信息(损失和指标)。

  4. 模型优化器状态。

  1. Model weights.
  2. Model architecture.
  3. Model compilation details (loss and metrics).
  4. Model optimizer state.

然后可以通过调用load_model()函数并传递文件名来加载保存的模型。函数将返回具有相同架构和权重的模型。

Saved model can then be loaded by calling the load_model() function and passing the filename. The function returns the model with the same architecture and weights.

示例:我运行了一个简单的模型,并使用model.save和用keras的load_model加载了。您可以从此处下载数据集。

Example: I have run a simple model and saved using model.save and the did the load with load_model of keras. You can download the dataset from here.

建立并保存模型:

# MLP for Pima Indians Dataset saved to single file
import numpy as np
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense

# load pima indians dataset
dataset = np.loadtxt("/content/pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# define model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Model Summary
model.summary()

# Fit the model
model.fit(X, Y, epochs=150, batch_size=10, verbose=0)

# evaluate the model
scores = model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

# save model and architecture to single file
model.save("model.h5")
print("Saved model to disk")

输出-

Model: "sequential_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_7 (Dense)              (None, 12)                108       
_________________________________________________________________
dense_8 (Dense)              (None, 8)                 104       
_________________________________________________________________
dense_9 (Dense)              (None, 1)                 9         
=================================================================
Total params: 221
Trainable params: 221
Non-trainable params: 0
_________________________________________________________________
acc: 77.08%
Saved model to disk

加载模型并评估以验证:

# load and evaluate a saved model
from numpy import loadtxt
from keras.models import load_model

# load model
model = load_model('model.h5')

# summarize model.
model.summary()

# load dataset
dataset = loadtxt("pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# evaluate the model
score = model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], score[1]*100))

输出-

Model: "sequential_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_7 (Dense)              (None, 12)                108       
_________________________________________________________________
dense_8 (Dense)              (None, 8)                 104       
_________________________________________________________________
dense_9 (Dense)              (None, 1)                 9         
=================================================================
Total params: 221
Trainable params: 221
Non-trainable params: 0
_________________________________________________________________
acc: 77.08%