gpt4 book ai didi

python - 神经网络的 Keras 模型 load_weights

转载 作者:太空狗 更新时间:2023-10-29 20:39:21 26 4
gpt4 key购买 nike

我正在使用 Keras 库在 Python 中创建神经网络。我已经加载了训练数据(txt 文件),启动了网络并“拟合”了神经网络的权重。然后我编写了代码来生成输出文本。这是代码:

#!/usr/bin/env python

# load the network weights
filename = "weights-improvement-19-2.0810.hdf5"
model.load_weights(filename)
model.compile(loss='categorical_crossentropy', optimizer='adam')

我的问题是:执行时会产生以下错误:

 model.load_weights(filename)
NameError: name 'model' is not defined

我添加了以下内容,但错误仍然存​​在:

from keras.models import Sequential
from keras.models import load_model

如有任何帮助,我们将不胜感激。

最佳答案

您需要先创建名为 model 的网络对象,编译它,然后调用 model.load_weights(fname)

工作示例:

from keras.models import Sequential
from keras.layers import Dense, Activation


def build_model():
model = Sequential()

model.add(Dense(output_dim=64, input_dim=100))
model.add(Activation("relu"))
model.add(Dense(output_dim=10))
model.add(Activation("softmax"))

# you can either compile or not the model
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
return model


model1 = build_model()
model1.save_weights('my_weights.model')


model2 = build_model()
model2.load_weights('my_weights.model')

# do stuff with model2 (e.g. predict())

保存和加载整个模型

在 Keras 中,我们可以像这样保存和加载整个模型(更多信息 here):

from keras.models import load_model

model1 = build_model()
model1.save('my_model.hdf5')

model2 = load_model('my_model.hdf5')
# do stuff with model2 (e.g. predict()

关于python - 神经网络的 Keras 模型 load_weights,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41859997/

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