[英]How to save keras model along with other data and load them altogether?
我有以下代码来训练keras神经网络
from keras import Sequential
from keras.layers import Dense
from keras.models import load_model
import numpy as np
class Model:
def __init__(self, data=None):
self.data = data
self.metrics = []
self.model = self.__build_model()
def __build_model(self):
model = Sequential()
model.add(Dense(4, activation='relu', input_shape=(3,)))
model.add(Dense(1, activation='relu'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
return model
def train(self, epochs):
self.model.fit(self.data[:, :-1], self.data[:,-1], epochs=epochs)
return self
def test(self, data):
self.metrics = self.model.evaluate(data[:, :-1], data[:, -1])
return self
def predict(self, input):
return self.model.predict(input)
def save(self, path):
self.model.save(path)
# I would like to save self.metrics at the same time
def load(self, path):
self.model = load_model(path)
if __name__ == '__main__':
train_data = np.random.rand(1000, 4)
test_data = np.random.rand(100, 4)
print("TRAINING, TESTING & SAVING..")
model = Model(train_data)\
.train(epochs=5)\
.test(test_data)\
.save('./model.h5')
print('LOADING model & PREDICTING..')
test_sample = np.random.rand(1, 3)
model = Model()
model.load('./model.h5')
# I can then do like:
test_output = model.predict(test_sample)
print(test_output)
# And want to get metrics which i had saved with it like:
metrics = model.metrics
print(metrics)
如您所见,它会将模型保存到h5文件中,但是仅保存keras模型。 我如何同时保存其他数据(如指标),然后在加载keras模型时也能够加载它们。
谢谢 !
您可以使用任何序列化框架来执行此操作。
import hickle
def save(self, path):
self.model.save(path)
hkl.dump(self.metrics, 'metrics.hkl', mode='w')
def load(self, path):
self.model = load_model(path)
self.metrics = hkl.load('metrics.hkl')
您也可以将其另存为单个文件,只需从指标和模型对象中列出一个列表或另一个对象即可。 我建议分开保存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.