介绍如何保存神经网络,这样以后想要用的时候直接提取就可以
保存模型的步骤
1.训练模型
2.保存模型
3.导入模型并应用
Demo.py
#训练模型
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.models import Sequential
from keras.layers import Dense
from keras.models import load_model
# create some data
X = np.linspace(-1, 1, 200)
np.random.shuffle(X) # randomize the data
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, ))
X_train, Y_train = X[:160], Y[:160] # first 160 data points
X_test, Y_test = X[160:], Y[160:] # last 40 data points
model = Sequential()
model.add(Dense(units=1, input_dim=1))
model.compile(loss='mse', optimizer='sgd')
for step in range(301):
cost = model.train_on_batch(X_train, Y_train)
#保存模型
# save
print 'test before save: ', model.predict(X_test[0:2])
model.save('my_model.h5') # HDF5 file, you have to pip3 install h5py if don't have it
del model # deletes the existing model
#导入模型并应用
# load
model = load_model('my_model.h5')
print 'test after load: ', model.predict(X_test[0:2])
#另外还有其他保存模型并调用的方式,
#第一种是只保存权重而不保存模型的结构。
# save and load weights
model.save_weights('my_model_weights.h5')
model.load_weights('my_model_weights.h5')
#第二种是用 model.to_json 保存完结构之后,然后再去加载这个json_string。
# save and load fresh network without trained weights
from keras.models import model_from_json
json_string = model.to_json()
model = model_from_json(json_string)
结果:
test before save: [[ 1.86730385]
[ 2.21450877]]
test after load: [[ 1.86730385]
[ 2.21450877]]