Reputation: 321
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:
#!/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.
Upvotes: 16
Views: 48250
Reputation: 3744
you need to first create the network object called model
, compile it and only after call the 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())
in Keras we can save & load the entire model like this (more info 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()
Upvotes: 31