2017-07-24 58 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

相關問題