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