神经网络的Keras模型load_weights

时间:2017-01-25 19:26:45

标签: python neural-network keras

我使用Keras库在python中创建神经网络。我已经加载了训练数据(txt文件),启动了网络和#34; fit"神经网络的权重。然后我编写了代码来生成输出文本。这是代码:

#!/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

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:17)

您需要先创建一个名为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"))
    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())