Hen*_*Hub 7 python machine-learning keras data-science tensorflow
我在 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")
Run Code Online (Sandbox Code Playgroud)
除了我在 Keras 中遇到这种只读模式 ValueError 之外。通过pip我在我的 Windows 10 笔记本电脑上安装了 Keras 和 Tensorflow,并在网上进行了更多的研究,这似乎是另一个关于同一问题的 SO 帖子,答案指出:
您必须设置和定义模型的架构,然后使用 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")
Run Code Online (Sandbox Code Playgroud)
在掌握机器学习方面,他们还展示了节省 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])
Run Code Online (Sandbox Code Playgroud)
2)通过以下命令保存整个模型:
model.save("kwhFinal.h5")
Run Code Online (Sandbox Code Playgroud)
在加载过程中,使用此命令加载模型:
from keras.models import load_model
model=load_model("kwhFinal.h5")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7862 次 |
| 最近记录: |