Keras儲存與載入模型(JSON+HDF5)
阿新 • • 發佈:2018-11-27
在Keras中,有時候需要對模型進行序列化與反序列化。進行模型序列化時,會將模型結果與模型權重儲存在不同的檔案中,模型權重通常儲存在HDF5檔案中,模型的結構可以儲存在JSON或者YAML檔案中。後二者方法大同小異,這裡以JSON為例說明一下Keras模型的儲存與載入。
from sklearn import datasets import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.utils import to_categorical from keras.models import model_from_json #匯入資料 dataset = datasets.load_iris() x = dataset.data Y = dataset.target #將標籤資料轉換為分類編碼 Y_labels = to_categorical(Y, num_classes=3) #設定隨機種子 seed = 7 np.random.seed(seed) #構建模型函式 def create_model(optimizer = 'rmsprop', init = 'glorot_uniform'): #構建模型 model = Sequential() model.add(Dense(units=4, activation='relu', input_dim=4, kernel_initializer=init)) model.add(Dense(units=6, activation='relu', kernel_initializer=init)) model.add(Dense(units=3, activation='softmax', kernel_initializer=init)) #編譯模型 model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model #構建模型 model = create_model() model.fit(x,Y_labels, epochs=200, batch_size=5, verbose=0) scores = model.evaluate(x,Y_labels, verbose=0) print('%s: %.2f%%' % (model.metrics_names[1], scores[1]*100)) #模型儲存JSON檔案 model_json = model.to_json() with open(r'F:\Python\pycharm\keras_deeplearning\model\modle.json', 'w') as file: file.write(model_json) #儲存模型權重值 model.save_weights('model.json.h5') #從JSON檔案中載入模型 with open(r'F:\Python\pycharm\keras_deeplearning\model\modle.json', 'r') as file: model_json1 = file.read() #載入模型 new_model = model_from_json(model_json1) new_model.load_weights('model.json.h5') #編譯模型 new_model.compile(loss='categorical_crossentropy', optimizer='rmsprop',metrics=['accuracy']) #評估載入之後的模型 scores1 = new_model.evaluate(x,Y_labels,verbose=0) print('%s: %.2f%%' % (model.metrics_names[1], scores1[1]*100))
通過載入模型的方式建立新的模型後,必須先編譯模型,然後使用載入後的模型對新資料進行預測。
這裡的JSON檔案內容如下:
{"class_name": "Sequential", "config": [{"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "batch_input_shape": [null, 4], "dtype": "float32", "units": 4, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Dense", "config": {"name": "dense_2", "trainable": true, "units": 6, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "Dense", "config": {"name": "dense_3", "trainable": true, "units": 3, "activation": "softmax", "use_bias": true, "kernel_initializer": {"class_name": "VarianceScaling", "config": {"scale": 1.0, "mode": "fan_avg", "distribution": "uniform", "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}], "keras_version": "2.2.2", "backend": "tensorflow"}