简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM