2

Can we save any of the created LSTM models themselves? I believe that “pickling” is the standard method to serialize python objects to a file. Ideally, I wanted to create a python module that contained one or more functions that either allowed me to specify an LSTM model to load or used a hard-coded pre-fit model to generate forecasts based on data passed in to initialize the model.

I tried to use it but gave me an error.

Code that I used:

    # create and fit the LSTM network
batch_size = 1
model = Sequential()
model.add(LSTM(50, batch_input_shape=(batch_size, look_back, 1), stateful=True, return_sequences=True))
model.add(Dropout(0.3))
model.add(Activation('relu'))
model.add(LSTM(50, batch_input_shape=(batch_size, look_back, 1), stateful=True)) 
model.add(Dropout(0.3))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('relu'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics = ['accuracy'])
for i in range(10):
    model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False)
    model.reset_states()

with open ('sequential.pickle','wb') as f:
    pickle.dump(model,f)

pickle_in = open ('sequential.pickle','rb')
model = pickle.load(pickle_in)

# make predictions
trainPredict = model.predict(trainX, batch_size=batch_size)
model.reset_states()
testPredict = model.predict(testX, batch_size=batch_size)
cs95
  • 379,657
  • 97
  • 704
  • 746
Ukesh
  • 43
  • 1
  • 7

1 Answers1

4

From the documentation:

It is not recommended to use pickle or cPickle to save a Keras model.

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.

To save your model, you'd need to call model.save:

model.save('model.h5')  # creates a HDF5 file 'model.h5'

Similarly, loading the model is done like this:

from keras.models import load_model
model = load_model('model.h5')
cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    @coldspeed Great help. Appreciated. – Ukesh Jul 25 '17 at 15:18
  • Looks like [this](https://stackoverflow.com/questions/4677012/python-cant-pickle-type-x-attribute-lookup-failed?rq=1) post is answering that. And that `dill` works, see [this](https://stackoverflow.com/questions/42168420/how-to-dill-pickle-to-file). – botenvouwer Jan 07 '19 at 14:02