cs0815
cs0815

Reputation: 17388

pickle Keras ANN

I am trying to use this code to fit an ANN using Keras and then pickle it:

early_stopping = EarlyStopping(monitor='val_loss', patience=4, mode='auto')
model = Sequential()
model.add(Dense(units=40, kernel_initializer='random_uniform', input_dim=x_train.shape[1], activation='relu'))
model.add(Dense(units=1, kernel_initializer='random_uniform', activation='sigmoid', W_regularizer=reg))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(x=x_train, y=y_train, epochs=1, validation_data=(x_val, y_val), callbacks=[early_stopping])

pickle_file_and_path = 'C:/Bla/DLModel20180816.sav'
pickle.dump(model, open(pickle_file_and_path, 'wb'))

Unfortunately, I get:

  pickle.dump(model, open(pickle_file_and_path, 'wb'))
TypeError: can't pickle _thread.RLock objects

Any ideas?

Upvotes: 0

Views: 1673

Answers (1)

sdcbr
sdcbr

Reputation: 7129

The canonical way of storing Keras models is to use the built-in model.save() method which will save the model into a HDF5 file.

Adapting your code:

model = Sequential()
model.add(Dense(units=40, kernel_initializer='random_uniform', input_dim=x_train.shape[1], activation='relu'))
model.add(Dense(units=1, kernel_initializer='random_uniform', activation='sigmoid', W_regularizer=reg))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(x=x_train, y=y_train, epochs=1, validation_data=(x_val, y_val), callbacks=[early_stopping])

# Save the model
model.save('./model.h5')

Afterwards, you can load it as follows:

from keras.models import load_model
model = load_model('./model.h5')

And start retraining or use the model for inference. Note that you can also store the only the weights with the save_weights() method. For the full documentation and more examples see the Keras website.

Upvotes: 1

Related Questions