训练后如何保存模型权重?
Keras提供:
model.save('weights.h5')`
模型对象由build_fn属性函数初始化,如何保存?
def model():
model = Sequential()
model.add(Dense(10, activation='relu', input_dim=5))
model.add(Dense(5, activation='relu'))
model.add(Dense(1, kernel_initializer='normal'))
model.compile(loss='mean_squared_error', optimizer='adam')
return model
if __name__ == '__main__':
`
X, Y = process_data()
print('Dataset Samples: {}'.format(len(Y)))
model = KerasRegressor(build_fn=model,
epochs=10,
batch_size=10,
verbose=1)
kfold = KFold(n_splits=2, random_state=seed)
results = cross_val_score(model, X, Y, cv=kfold)
print('Results: {0}.2f ({1}.2f MSE'.format(results.mean(), results.std()))
答案 0 :(得分:7)
cross_val_score
克隆提供的估计量,使它们适合训练倍数,分数适合测试倍数。因此,从本质上讲,您的实际模型尚未拟合。
所以首先您需要使模型适合数据:
model.fit(X, Y)
然后,您可以使用基础的model
属性(实际上存储了keras模型)来调用save()
或save_weights()
方法。
model.model.save('saved_model.h5')
现在,当您想再次加载模型时,请执行以下操作:
from keras.models import load_model
# Instantiate the model as you please (we are not going to use this)
model2 = KerasRegressor(build_fn=model_build_fn, epochs=10, batch_size=10, verbose=1)
# This is where you load the actual saved model into new variable.
model2.model = load_model('hh.h5')
# Now you can use this to predict on new data (without fitting model2, because it uses the older saved model)
model2.predict(X)