我们训练完模型之后,一般会需要保存模型或者只保存权重文件。可以利用keras中的回调函数ModelCheckpoint进行保存。
keras.callbacks.ModelCheckpoint(
filepath,
monitor='val_loss',
verbose=0,
save_best_only=True,
save_weights_only=False,
mode='auto',
period=1
)
1. filename:模型保存在本地的路径
2. monitor:需要监视的值,val_accuracy、val_loss或者accuracy
3. verbose:信息展示模式
4. save_best_only:当设置为True时,表示当模型这次epoch的训练评判结果(monitor的监测值)比上一次保存训练时的结果有提升时才进行保存。
5. mode:‘auto’,‘min’,‘max’之一,在save_best_only=True时决定性能最佳模型的评判准则,例如,当监测值为val_acc时,模式应为max,当检测值为val_loss时,模式应为min。在auto模式下,评价准则由被监测值的名字自动推断。
6. save_weights_only:若设置为True,占用内存小(只保存模型权重),但下次想调用的话,需要搭建和训练时一样的网络。若设置为False,占用内存大(包括了模型结构和配置信息),下次调用可以直接载入,不需要再次搭建神经网络结构。
7. period:填写 int 值,如果填写 period=3,指模型每训练3个epoch,进行保存一次。
保存.h5文件,以手写数字mnist为例,代码如下:
# -*- coding: utf-8 -*-
import numpy #导入数据库
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
from keras.callbacks import EarlyStopping,ModelCheckpoint
from keras.models import load_model
seed = 7 #设置随机种子
numpy.random.seed(seed)
(X_train, y_train), (X_test, y_test) = mnist.load_data(path='mnist.npz') #加载数据
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32')
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
#数据集是3维的向量(instance length,width,height).对于多层感知机,模型的输入是二维的向量,因此这
#里需要将数据集reshape,即将28*28的向量转成784长度的数组。可以用numpy的reshape函数轻松实现这个过
#程。
#给定的像素的灰度值在0-255,为了使模型的训练效果更好,通常将数值归一化映射到0-1。
X_train = X_train / 255
X_test = X_test / 255
#最后,模型的输出是对每个类别的打分预测,对于分类结果从0-9的每个类别都有一个预测分值,表示将模型
#输入预测为该类的概率大小,概率越大可信度越高。由于原始的数据标签是0-9的整数值,通常将其表示成#0ne-hot向量。如第一个训练数据的标签为5,one-hot表示为[0,0,0,0,0,1,0,0,0,0]。
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
#现在需要做得就是搭建神经网络模型了,创建一个函数,建立含有一个隐层的神经网络。
# define baseline model
def baseline_model():
# create model
model = Sequential()
model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics=['accuracy'])
return model
#型的隐含层含有784个节点,接受的输入长度也是784(28*28),最后用softmax函数将预测结果转换为标签
#的概率值。
#将训练数据fit到模型,设置了迭代轮数,每轮200个训练样本,将测试集作为验证集,并查看训练的效果。
# build the model
model = baseline_model()
# 参数:
# filename:字符串,保存模型的路径
# monitor:需要监视的值
# verbose:信息展示模式,0或1
# save_best_only:当设置为True时,将只保存在验证集上性能最好的模型
filepath="model_{epoch:02d}-{val_accuracy:.2f}.h5"
checkpoint=ModelCheckpoint(
filepath=filepath,
monitor='val_accuracy',
save_best_only=True,
verbose=1,
save_weights_only=True,
period=3
)
# Fit the model
history=model.fit(X_train, y_train, validation_data=(X_test, y_test),
epochs=30, batch_size=200,
callbacks=[checkpoint],verbose=2)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=1)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))
当save_weights_only=False,保存了整个模型,保存 .h5 文件结果如下:
可以采用from keras.model import load_model ,然后model=load_model(.h5文件本地保存路径)进行调用,不再需要搭建网络代码如下:
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import numpy #导入数据库
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
from keras.models import load_model
seed = 7 #设置随机种子
numpy.random.seed(seed)
(X_train, y_train), (X_test, y_test) = mnist.load_data(path='mnist.npz') #加载数据
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32')
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
#数据集是3维的向量(instance length,width,height).对于多层感知机,模型的输入是二维的向量,因此这
#里需要将数据集reshape,即将28*28的向量转成784长度的数组。可以用numpy的reshape函数轻松实现这个过
#程。
#给定的像素的灰度值在0-255,为了使模型的训练效果更好,通常将数值归一化映射到0-1。
X_train = X_train / 255
X_test = X_test / 255
#最后,模型的输出是对每个类别的打分预测,对于分类结果从0-9的每个类别都有一个预测分值,表示将模型
#输入预测为该类的概率大小,概率越大可信度越高。由于原始的数据标签是0-9的整数值,通常将其表示成#0ne-hot向量。如第一个训练数据的标签为5,one-hot表示为[0,0,0,0,0,1,0,0,0,0]。
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
#型的隐含层含有784个节点,接受的输入长度也是784(28*28),最后用softmax函数将预测结果转换为标签
#的概率值。
#将训练数据fit到模型,设置了迭代轮数,每轮200个训练样本,将测试集作为验证集,并查看训练的效果。
model=load_model('model_09-0.98.h5')
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=1)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))
当save_weights_only=True,只保存了模型的权重文件,需要搭建一个和权重文件一样的网络,然后使用model.load_weights('文件保存路径') 调用.h5权重文件:
# -*- coding: utf-8 -*-
import numpy #导入数据库
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
seed = 7 #设置随机种子
numpy.random.seed(seed)
(X_train, y_train), (X_test, y_test) = mnist.load_data(path='mnist.npz') #加载数据
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32')
X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
#数据集是3维的向量(instance length,width,height).对于多层感知机,模型的输入是二维的向量,因此这
#里需要将数据集reshape,即将28*28的向量转成784长度的数组。可以用numpy的reshape函数轻松实现这个过
#程。
#给定的像素的灰度值在0-255,为了使模型的训练效果更好,通常将数值归一化映射到0-1。
X_train = X_train / 255
X_test = X_test / 255
#最后,模型的输出是对每个类别的打分预测,对于分类结果从0-9的每个类别都有一个预测分值,表示将模型
#输入预测为该类的概率大小,概率越大可信度越高。由于原始的数据标签是0-9的整数值,通常将其表示成#0ne-hot向量。如第一个训练数据的标签为5,one-hot表示为[0,0,0,0,0,1,0,0,0,0]。
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
#现在需要做得就是搭建神经网络模型了,创建一个函数,建立含有一个隐层的神经网络。
# define baseline model
def baseline_model():
# create model
model = Sequential()
model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics=['accuracy'])
return model
#
#型的隐含层含有784个节点,接受的输入长度也是784(28*28),最后用softmax函数将预测结果转换为标签
#的概率值。
#将训练数据fit到模型,设置了迭代轮数,每轮200个训练样本,将测试集作为验证集,并查看训练的效果。
model = baseline_model()
model.load_weights('model_weights_only_09-0.98.h5')
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=1)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))