Keras load_weights model for Neural Net

I am using the Keras library to create a neural network in python. I downloaded the training data (txt file), initiated the network and “customized” the scales of the neural network. Then I wrote 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: during execution, the following error appears:

 model.load_weights(filename)
 NameError: name 'model' is not defined

I added the following, but the error still persists:

from keras.models import Sequential
from keras.models import load_model

Any help would be appreciated.

+4
source share
1 answer

you need to first create a network object with a name model, compile it, and only after the callmodel.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"))
    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())
+10
source

Source: https://habr.com/ru/post/1667806/


All Articles