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.
A Sequential model is appropriate for a plain stack of layers where each layer has exactly one input tensor and one output tensor. Schematically, the following Sequential model: # Define Sequential model with 3 layers model = keras. Sequential( [ layers. Dense(2, activation="relu", name="layer1"), layers.
Save Your Neural Network Model to JSONThis can be saved to a file and later loaded via the model_from_json() function that will create a new model from the JSON specification. The weights are saved directly from the model using the save_weights() function and later loaded using the symmetrical load_weights() function.
H5 is a file format to store structured data, it's not a model by itself. Keras saves models in this format as it can easily store the weights and model configuration in a single file.14-Jul-2020.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With