gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:02:46 26 4
gpt4 key购买 nike

我在 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 ,答案是:

You have to set and define the architecture of your model and then use model.load_weights

但我对这一点的理解还不足以从答案中重新创建代码(链接到 git gist)。下面是我在 Linux 操作系统上运行以创建模型的 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,但我不确定这是否有助于定义模型架构...

最佳答案

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

您有两个解决方案:

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")

关于python - 在 Keras 中使用 load_weights 加载模型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55049208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com