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

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

我们可以自己保存任何创建的 LSTM 模型吗?我相信“酸洗”是将 python 对象序列化到文件的标准方法。理想情况下,我想创建一个 python 模块,其中包含一个或多个函数,这些函数允许我指定要加载的 LSTM 模型或使用硬编码预拟合模型根据传入的数据生成预测以进行初始化该模型。

我尝试使用它,但出现错误。

我使用的代码:

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

来自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.

要保存您的模型,您需要调用 model.save:

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

同样,加载模型是这样完成的:

from keras.models import load_model
model = load_model('model.h5')