Keras保存模型
- 2019 年 11 月 4 日
- 筆記
學習一時爽,一直學習一直爽
Hello,大家好,我是 もうり,一個從無到有的技術+語言小白。
一旦你利用Keras完成了訓練,你可以將你的網絡保存在HDF5裏面。
keras的模型保存分為多種情況。
一、不保存模型只顯示大概結構 model.summary() 這個函數會打印模型結構,但是僅僅是打印到控制台。
keras.utils.plot_model() 使用graphviz中的dot.exe生成網絡結構拓撲圖
二、保存模型結構 keras.models.Model
對象的to_json,to_yaml只保存模型結構,加載時使用keras.models.model_from_json(),keras.models.model_from_yaml()
keras.model.get_config()返迴文本形式的配置 使用keras.model.model_from_config可以加載模型。
三、保存全部結構(最常用的方法) keras.core.saving.py這個文件十分重要,keras的模型保存、加載都需要這個文件。 但是不建議直接使用這個文件,因為keras中的Model對象和models模塊會調用這個文件。 keras.core包下的內容一般供內部使用,不暴露給使用者。
Model對象提供了save()和save_wights()兩個方法。
只需要導入
from keras.models import model_from_json
就是這麼簡單
基於Iris數據集如何保存model
''' @author: 毛利 ''' 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 # 二分類 將標籤轉換成分類編碼(每一列代表一類,是為1,否為0) Y_labels = to_categorical(Y, num_classes=3) seed = 4 np.random.seed(seed) # 這裡使用rmsprop優化器,adam也行 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)) # categorical:分類的 crossentropy:交叉熵 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) # evaluate: 評價 scores = model.evaluate(x, Y_labels, verbose=0) print('%s: %.2f%%' % (model.metrics_names[1], scores[1]*100))
可以保存yaml
from keras.models import model_from_yaml
''' @author: 毛利 ''' 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_yaml dataset = datasets.load_iris() x = dataset.data Y = dataset.target # 將標籤轉換成分類編碼(每一列代表一類,是為1,否為0) Y_labels = to_categorical(Y, num_classes=3) seed = 4 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)) # categorical:分類的 crossentropy:交叉熵 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) # evaluate: 評價 scores = model.evaluate(x, Y_labels, verbose=0) print('%s: %.2f%%' % (model.metrics_names[1], scores[1]*100)) # 將模型保存成YAML文件 model_yaml = model.to_yaml() with open('../model/model.yaml', 'w') as file: file.write(model_yaml) # 保存模型權重值 model.save_weights('../model/model.yaml.h5') # 從YAML文件中加載模型 with open('../model/model.yaml', 'r') as file: model_yaml = file.read() # 加載模型 new_model = model_from_yaml(model_yaml) new_model.load_weights('../model/model.yaml.h5') # 必須先編譯模型 new_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # 評估從YAML文件中加載的模型 scores = new_model.evaluate(x, Y_labels, verbose=0) print('%s: %.2f%%' % (new_model.metrics_names[1], scores[1]*100))