Python 用于神经网络的 Keras 模型 load_weights

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41859997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:45:34  来源:igfitidea点击:

Keras model load_weights for Neural Net

pythonneural-networkkeras

提问by Deadulus

I'm using the Keras library to create a neural network in python. I have loaded the training data (txt file), initiated the network and "fit" the weights of the neural network. I have then written code to generate the output text. Here is the code:

我正在使用 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')

My problem is: on execution the following error is produced:

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

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

I have added the following but the error still persists:

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

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

Any help would be appreciated.

任何帮助,将不胜感激。

回答by ShmulikA

you need to first create the network object called model, compile it and only after call the model.load_weights(fname)

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

working example:

工作示例:

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

Save & Load an Entire Model

保存和加载整个模型

in Keras we can save & load the entire model like this (more info here):

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

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