PicklingError:不能使< class'module'>的pickle:内置的属性查找模块失败 [英] PicklingError: Can't pickle <class 'module'>: attribute lookup module on builtins failed

查看:145
本文介绍了PicklingError:不能使< class'module'>的pickle:内置的属性查找模块失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我使用的代码:

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

推荐答案

来自

不建议使用pickle或cPickle保存Keras模型.

您可以使用model.save(filepath)将Keras模型保存为单个 HDF5文件将包含:

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

  • 模型的体系结构,允许重新创建模型
  • 模型的权重
  • 培训配置(损失,优化程序)
  • 优化器的状态,可以从您上次中断的地方继续进行准确的训练.然后可以使用keras.models.load_model(filepath) 重新实例化模型.
  • 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:

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

这篇关于PicklingError:不能使< class'module'>的pickle:内置的属性查找模块失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆