2017-07-24 71 views
0

我们可以保存任何创建的LSTM模型本身吗?我相信“酸洗”是将python对象序列化到文件的标准方法。理想情况下,我想创建一个包含一个或多个函数的python模块,这些函数或者允许我指定LSTM模型来加载或使用硬编码的预拟合模型,以基于传入的数据生成预测以初始化模型。PicklingError:Can not pickle <class'module'>:内建属性查找模块失败

我试图使用它,但给了我一个错误。我用

代码:

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

回答

2

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

@coldspeed很好的帮助。赞赏。 – Ukesh

相关问题