keras 中模型的保存及重用


深度学习中如何保存最佳模型,如何重用已经保存的模型?本文主要介绍Keras 保存及重用模型的方法

保存模型

如下,我们预定义保存的hdf5文件名,再初始化ModelCheckpoint,将其加入Keras的callback里(即每个batch结束后做的事情),那么模型就会在每次batch结束后对比,保存最好的模型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from keras.callbacks import ModelCheckpoint

# create model
model = Sequential()
model.add(...)
model.add(...)
model.add(...)
# Compile model
model.compile(...)
# checkpoint
filepath="weights-{epoch:02d}-{val_acc:.2f}.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
# Fit the model
model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, callbacks=[checkpoint], verbose=0)

结束后,我们会得到如下的结果,

1
2
3
4
5
...
weights-53-0.76.hdf5
weights-71-0.76.hdf5
weights-77-0.78.hdf5
weights-99-0.78.hdf5

如果我们只想保存一个最好的模型,那么把保存文件名字固定为filepath="weights.best.hdf5"即可。

load模型

注意,之前保存的只是模型的weights,重新load需要再次定义模型结构再load weights并再次combine,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
from keras.callbacks import ModelCheckpoint
# create model
model = Sequential()
model.add(...)
model.add(...)
model.add(...)
# load weights
model.load_weights("weights.best.hdf5")
# Compile model
model.compile(...)
# estimate accuracy
scores = model.evaluate(X, Y, verbose=0)
print('{}: {:.2%}'.format(model.metrics_names[1], scores[1]))

如果之前选择了连模型结构也一起保存(即在ModelCheckpoint中选择 save_weights_only=False),那么load就很简单,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from keras.callbacks import ModelCheckpoint
from keras.models import load_model

# create model
model = Sequential()
model.add(...)
model.add(...)
model.add(...)
# Compile model
model.compile(...)
# checkpoint
filepath="weights-best.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max', save_weights_only=False)

# Fit the model
model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, callbacks=[checkpoint], verbose=0)

# Load the model
model= load_model(filepath)
scores=model.evaluate(X, Y,verbose=0)
print('{}: {:.2%}'.format(model.metrics_names[1], scores[1]))