0

I have a simple code snippet to train a model but, when I use pickle to save the model for future use, it gives me an error message:

cannot pickle thread.LOCK objects

I used the pickle in more than one format yet it gives me the same error.

import pickle

model = keras.Sequential([
    keras.layers.Dense(SHAPE, input_shape=(SHAPE,)),
    keras.layers.Dense(300, activation='sigmoid'),
    keras.layers.Dense(10, activation='softmax')
])


#******************    COMPILING THE MODE        *****************
LEARNING_RATE = 0.0005
model.compile(optimizer=keras.optimizers.Adam(lr=LEARNING_RATE),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']              
             )

# ***********      TRAINING THE MODEL   **********
EPOCHS = 20
BATCH_SIZE=50

history_original_data = model.fit(X_original_train_images, y_original_train_labels, epochs=EPOCHS, batch_size=BATCH_SIZE) 
hist_original=history_original_data.history


### PICKLE TO SAVE THE MODEL TO BE USED WITHOU PRO-TRAINING IT
pickname ="SequentialNeuroNetwork.pkl"
PickleSeq = open(pickname, 'wb')
pickle.dump(model, PickleSeq)
PickleSeq.close()

I was expecting the above code snippet to run smoothly but it is taking the toll out on me.

jdehesa
  • 58,456
  • 7
  • 77
  • 121
Samuel
  • 7
  • 4
  • Hi there! People are much more inclined to help you (and able to help) if you post the corresponding error message, too. Make sure to edit your post according to the rules in [ask] and [mcve]. – dennlinger Jul 11 '19 at 11:00
  • https://stackoverflow.com/questions/48295661/how-to-pickle-keras-model –  Jul 11 '19 at 12:19
  • It is not recommended to save a keras model as pickle file (Preferred for sklearn). Keras models should be save as hdf5 files. – Trollsors Jul 11 '19 at 13:47

1 Answers1

0

Which version of keras are you using? I am almost sure that old versions do not support pickle.

Alternatively, It is recommended to use model.save() to save your models in keras. As it is stated in page FAQ for keras:

You can use model.save(filepath) to save a Keras model into a single HDF5 file which will contain:

  • the architecture of the model, allowing to re-create the model
  • the weights of the model
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.

You can then use keras.models.load_model(filepath) to reinstantiate your model. load_model will also take care of compiling the model using the saved training configuration (unless the model was never compiled in the first place).

Source: https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model

Victor Oliveira
  • 216
  • 1
  • 6