PicklingError: Can't pickle <class 'module'>: attribute lookup module on builtins failed

梦想与她 提交于 2019-12-24 10:58:01

问题


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)

回答1:


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')


来源:https://stackoverflow.com/questions/45289892/picklingerror-cant-pickle-class-module-attribute-lookup-module-on-builtin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!