简体   繁体   中英

How do I use pickle in this code snippet?

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.

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

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