0 votes
1 view
in Data Science by (15.8k points)
recategorized by

How to load a model from an HDF5 file in Keras?

What I tried:

model = Sequential()

model.add(Dense(64, input_dim=14, init='uniform'))

model.add(LeakyReLU(alpha=0.3))

model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))

model.add(Dropout(0.5))

model.add(Dense(64, init='uniform'))

model.add(LeakyReLU(alpha=0.3))

model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))

model.add(Dropout(0.5))

model.add(Dense(2, init='uniform'))

model.add(Activation('softmax'))

sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)

model.compile(loss='binary_crossentropy', optimizer=sgd)

checkpointer = ModelCheckpoint(filepath="/weights.hdf5", verbose=1, save_best_only=True)

model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose = 2, callbacks=[checkpointer])

The above code successfully saves the best model to a file named weights.hdf5. What I want to do is then load that model. The below code shows how I tried to do so:

model2 = Sequential()

model2.load_weights("/Users/Desktop/SquareSpace/weights.hdf5")

This is the error I get:

IndexError: list index out of range

1 Answer

0 votes
by (33.2k points)

You can simply use load_model from keras.model class. 

For example:

from keras.models import load_model

model = load_model('model.h5')

This code will simply import your model from the given hdf5 file into the model variable.

If you wish to learn Python, then check out this Python Course by Intellipaat.

Hope this answer helps.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...