在Keras中使用load_weights加载模型时出错

时间:2019-03-07 17:01:09

标签: python tensorflow machine-learning keras data-science

我在Linux平台上用keras(回归)训练了模型,并用model.save_weights("kwhFinal.h5")

保存了模型。

然后我希望将完整的保存的模型带到Windows 10笔记本电脑上的Python 3.6中,并与IDLE一起使用:

from keras.models import load_model

# load weights into new model
loaded_model.load_weights("kwhFinal.h5")
print("Loaded model from disk")

除非我使用Keras进入此只读模式ValueError。通过pip,我在Windows 10笔记本电脑上安装了Keras&Tensorflow,并在网上进行了更多other SO post about the same issue研究,答案是:

  

您必须设置和定义模型的架构,然后使用   model.load_weights

但是我对这一点还不够了解,无法从答案中重新创建代码(链接到git gist)。这是我在Linux OS上运行的Keras脚本,用于创建模型。有人可以给我一些有关如何定义体系结构的提示,以便我可以使用此模型在Windows 10笔记本电脑上进行预测吗?

#https://machinelearningmastery.com/custom-metrics-deep-learning-keras-python/
#https://machinelearningmastery.com/save-load-keras-deep-learning-models/
#https://machinelearningmastery.com/regression-tutorial-keras-deep-learning-library-python/


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras import backend
from keras.models import model_from_json
import os



def rmse(y_true, y_pred):
    return backend.sqrt(backend.mean(backend.square(y_pred - y_true), axis=-1))

# 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 = df.drop(['kWh'],1)
Y = df['kWh']

offset = int(X.shape[0] * 0.7)
X_train, Y_train = X[:offset], Y[:offset]
X_test, Y_test = X[offset:], Y[offset:]


model = Sequential()
model.add(Dense(60, input_dim=7, kernel_initializer='normal', activation='relu'))
model.add(Dense(55, kernel_initializer='normal', activation='relu'))
model.add(Dense(50, kernel_initializer='normal', activation='relu'))
model.add(Dense(45, kernel_initializer='normal', activation='relu'))
model.add(Dense(30, kernel_initializer='normal', activation='relu'))
model.add(Dense(20, kernel_initializer='normal', activation='relu'))
model.add(Dense(1, kernel_initializer='normal'))
model.summary()

model.compile(loss='mse', optimizer='adam', metrics=[rmse])

# train model
history = model.fit(X_train, Y_train, epochs=5, batch_size=1,  verbose=2)

# plot metrics
plt.plot(history.history['rmse'])
plt.title("kWh RSME Vs Epoch")
plt.show()

# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

model.save_weights("kwhFinal.h5")
print("[INFO] Saved model to disk")

在精通机器学习方面,他们还演示了如何保存YML和Json,但我不确定这是否有助于定义模型体系结构...

2 个答案:

答案 0 :(得分:0)

您正在保存权重,而不是整个模型。模型不只是权重,还包括架构,损失,指标等。

您有两种解决方案:

1)保存权重:在这种情况下,在加载模型时,您将需要重新创建模型,加载权重然后编译模型。您的代码应如下所示:

model = Sequential()
model.add(Dense(60, input_dim=7, kernel_initializer='normal', activation='relu'))
model.add(Dense(55, kernel_initializer='normal', activation='relu'))
model.add(Dense(50, kernel_initializer='normal', activation='relu'))
model.add(Dense(45, kernel_initializer='normal', activation='relu'))
model.add(Dense(30, kernel_initializer='normal', activation='relu'))
model.add(Dense(20, kernel_initializer='normal', activation='relu'))
model.add(Dense(1, kernel_initializer='normal'))
model.load_weights("kwhFinal.h5")
model.compile(loss='mse', optimizer='adam', metrics=[rmse])

2)通过此命令保存整个模型:

model.save("kwhFinal.h5")

在加载过程中,请使用以下命令加载模型:

from keras.models import load_model
model=load_model("kwhFinal.h5")

答案 1 :(得分:0)

首先将load_model从keras更改为tensorflow.keras,即

from tensorflow.keras.models import load_model

但是即使那样,如果模型加载显示类似 KeyError: 'sample_weight_mode'的错误,请执行以下操作

from tensorflow.keras.models import load_model

model = load_model('model.h5', compile = False)