我們以MNIST手寫數字識別為例
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模型。
是否需要多次編譯?
除非我們要更改其中之一:損失函數、優化器 / 學習率、度量
又或者我們加載了尚未編譯的模型。或者您的加載/保存方法沒有考慮以前的編譯。
再次compile的后果?
如果再次編譯模型,將會丟失優化器狀態.
這意味着您的訓練在開始時會受到一點影響,直到調整學習率,動量等為止。但是絕對不會對重量造成損害(除非您的初始學習率如此之大,以至於第一次訓練步驟瘋狂地更改微調的權重)。