Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras model load_weights for Neural Net

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.

like image 463
Deadulus Avatar asked Jan 25 '17 19:01

Deadulus


People also ask

What is the meaning of model Sequentil () in Keras?

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.

How do I save a neural network model in python Keras?

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.

What is H5 model?

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.


1 Answers

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

Save & Load an Entire Model

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()
like image 123
ShmulikA Avatar answered Sep 18 '22 19:09

ShmulikA