Keras保存模型並載入模型繼續訓練

咱們以MNIST手寫數字識別爲例json

import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
 
# 載入數據
(x_train,y_train),(x_test,y_test) = mnist.load_data()
# (60000,28,28)
print('x_shape:',x_train.shape)
# (60000)
print('y_shape:',y_train.shape)
# (60000,28,28)->(60000,784)
x_train = x_train.reshape(x_train.shape[0],-1)/255.0
x_test = x_test.reshape(x_test.shape[0],-1)/255.0
# 換one hot格式
y_train = np_utils.to_categorical(y_train,num_classes=10)
y_test = np_utils.to_categorical(y_test,num_classes=10)
 
# 建立模型,輸入784個神經元,輸出10個神經元
model = Sequential([
        Dense(units=10,input_dim=784,bias_initializer='one',activation='softmax')
    ])
 
# 定義優化器
sgd = SGD(lr=0.2)
 
# 定義優化器,loss function,訓練過程當中計算準確率
model.compile(
    optimizer = sgd,
    loss = 'mse',
    metrics=['accuracy'],
)
 
# 訓練模型
model.fit(x_train,y_train,batch_size=64,epochs=5)
 
# 評估模型
loss,accuracy = model.evaluate(x_test,y_test)
 
print('\ntest loss',loss)
print('accuracy',accuracy)
 
# 保存模型
model.save('model.h5')   # HDF5文件,pip install h5py

 

載入初次訓練的模型,再訓練

import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
from keras.models import load_model
# 載入數據
(x_train,y_train),(x_test,y_test) = mnist.load_data()
# (60000,28,28)
print('x_shape:',x_train.shape)
# (60000)
print('y_shape:',y_train.shape)
# (60000,28,28)->(60000,784)
x_train = x_train.reshape(x_train.shape[0],-1)/255.0
x_test = x_test.reshape(x_test.shape[0],-1)/255.0
# 換one hot格式
y_train = np_utils.to_categorical(y_train,num_classes=10)
y_test = np_utils.to_categorical(y_test,num_classes=10)
 
# 載入模型
model = load_model('model.h5')
 
# 評估模型
loss,accuracy = model.evaluate(x_test,y_test)
 
print('\ntest loss',loss)
print('accuracy',accuracy)
 
# 訓練模型
model.fit(x_train,y_train,batch_size=64,epochs=2)
 
# 評估模型
loss,accuracy = model.evaluate(x_test,y_test)
 
print('\ntest loss',loss)
print('accuracy',accuracy)
 
# 保存參數,載入參數
model.save_weights('my_model_weights.h5')
model.load_weights('my_model_weights.h5')
# 保存網絡結構,載入網絡結構
from keras.models import model_from_json
json_string = model.to_json()
model = model_from_json(json_string)
 
print(json_string)

關於compile和load_model()的使用順序

這一段落主要是爲了解決咱們fit、evaluate、predict以前仍是以後使用compile。想要弄明白,首先咱們要清楚compile在程序中是作什麼的?都作了什麼?網絡

compile作什麼?函數

compile定義了loss function損失函數、optimizer優化器和metrics度量。它與權重無關,也就是說compile並不會影響權重,不會影響以前訓練的問題。學習

若是咱們要訓練模型或者評估模型evaluate,則須要compile,由於訓練要使用損失函數和優化器,評估要使用度量方法;若是咱們要預測,則沒有必要compile模型。優化

是否須要屢次編譯?lua

除非咱們要更改其中之一:損失函數、優化器 / 學習率、度量spa

又或者咱們加載了還沒有編譯的模型。或者您的加載/保存方法沒有考慮之前的編譯。code

再次compile的後果?blog

若是再次編譯模型,將會丟失優化器狀態.ip

這意味着您的訓練在開始時會受到一點影響,直到調整學習率,動量等爲止。可是絕對不會對重量形成損害(除非您的初始學習率如此之大,以致於第一次訓練步驟瘋狂地更改微調的權重)。