KerasRegressor 将模型序列化/保存为 .h5df

数据挖掘 Python 深度学习 喀拉斯 回归
2022-02-15 22:53:53

我一直在使用来自 machinelearningmastery 的Keras 回归脚本,我想将模型保存为 .h5 文件。

Machinelearningmastery 还有另一个保存模型/泡菜的教程,但是脚本是用 Keras 中的model.fit()方法编写的……但是我使用的脚本是通过调用函数来定义模型的。

有人可以告诉我如何将此模型保存为 .h5df 吗?

import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import matplotlib.pyplot as plt
import math
from sklearn.preprocessing import MinMaxScaler


# load dataset
dataset = pd.read_csv("joinedRuntime2.csv", index_col='Date', parse_dates=True)

print(dataset.shape)
print(dataset.dtypes)
print(dataset.columns)

# shuffle dataset
df = dataset.sample(frac=1.0)

# split into input (X) and output (Y) variables
X = np.array(df.drop(['kWh'],1))
Y = np.array(df['kWh'])


def wider_model():
    # create model
    model = Sequential()
    model.add(Dense(20, input_dim=7, kernel_initializer='normal', activation='relu'))
    #model.add(Dense(28, kernel_initializer='normal', activation='relu'))
    #model.add(Dense(21, kernel_initializer='normal', activation='relu'))
    #model.add(Dense(14, kernel_initializer='normal', activation='relu'))
    model.add(Dense(10, kernel_initializer='normal', activation='relu'))
    model.add(Dense(1, kernel_initializer='normal'))
    # Compile model
    model.compile(loss='mean_squared_error', optimizer='adam')
    return model


# fix random seed for reproducibility
seed = 7
np.random.seed(seed)
estimators = []
estimators.append(('standardize', StandardScaler()))
estimators.append(('mlp', KerasRegressor(build_fn=wider_model, epochs=200, batch_size=5, verbose=0)))
pipeline = Pipeline(estimators)
kfold = KFold(n_splits=10, random_state=seed)
results = cross_val_score(pipeline, X, Y, cv=kfold)
print("Wider: %.2f (%.2f) MSE" % (results.mean(), results.std()))
print("RMSE", math.sqrt(results.std()))
2个回答

引用 Keras 的官方页面

建议使用 pickle 或 cPickle 来保存 Keras 模型

您可以使用 model.save(filepath) 将 Keras 模型保存到单个 HDF5 文件中,该文件将包含:

  • 模型的架构,允许重新创建模型
  • 模型的权重
  • 训练配置(损失、优化器)
  • 优化器的状态,允许在您停止的地方恢复训练。

编辑后,听起来真正的问题是您正在使用 sklearn keras 包装器和 sklearn 管道。

要从管道访问实际的 NN,请使用stepsornamed_steps属性:
https ://scikit-learn.org/stable/modules/compose.html#pipeline

然后,要保存包装的 KerasRegressor 模型,请使用model_name.model.save()
https ://stackoverflow.com/questions/40396042/how-to-save-scikit-learn-keras-model-into-a-persistence-file-pickle-hd5-json -ya#40397312
https://github.com/keras-team/keras/issues/4274