我需要对LSTM使用Bagging方法,对时间序列数据进行培训。我已经定义了模型库,并使用KerasRegressor链接到scikit-learn。但是具有AttributeError:'KerasRegressor'对象没有属性'loss'。我该如何解决?
更新:我使用了Manoj Mohan的方法(在第一个评论中),并且在拟合步骤中成功了。但是,当我将Manoj Mohan的类修改为
时,就会出现TypeError问题。class MyKerasRegressor(KerasRegressor):
def fit(self, x, y, **kwargs):
x = np.expand_dims(x, -2)
super().fit(x, y, **kwargs)
def predict(self, x, **kwargs):
x = np.expand_dims(x, -2)
super().predict(x, **kwargs)
它解决了与(.fit())相同的predict()的尺寸问题。 问题是:
TypeError Traceback (most recent call last)
<ipython-input-84-68d76cb73e8b> in <module>
----> 1 pred_bag = bagging_model.predict(x_test)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
完整脚本:
def model_base_LSTM():
model_cii = Sequential()
# Make layers
model_cii.add(CuDNNLSTM(50, return_sequences=True,input_shape=((1, 20))))
model_cii.add(Dropout(0.4))
model_cii.add(CuDNNLSTM(50, return_sequences=True))
model_cii.add(Dropout(0.4))
model_cii.add(CuDNNLSTM(50, return_sequences=True))
model_cii.add(Dropout(0.4))
model_cii.add(CuDNNLSTM(50, return_sequences=True))
model_cii.add(Dropout(0.4))
model_cii.add(Flatten())
# Output layer
model_cii.add(Dense(1))
# Compile
model_cii.compile(optimizer = 'adam', loss = 'mean_squared_error', metrics=['accuracy'])
return model_cii
model = MyKerasRegressor(build_fn = model_base_LSTM, epochs=100, batch_size =70)
bagging_model = BaggingRegressor(base_estimator=model, n_estimators=10)
train_model = bagging_model.fit(x_train, y_train)
bagging_model.predict(x_test)
Output:
TypeError Traceback (most recent call last)
<ipython-input-84-68d76cb73e8b> in <module>
----> 1 pred_bag = bagging_model.predict(x_test)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
答案 0 :(得分:1)
model_base_LSTM()
方法中有错误。替换
return model
与
return model_cii
修复“检查输入时出错”的错误,可以添加一个额外的尺寸。这也解决了scikit-learn(2维)与Keras LSTM(3维)问题。创建KerasRegressor的子类来处理尺寸不匹配。
class MyKerasRegressor(KerasRegressor):
def fit(self, x, y, **kwargs):
x = np.expand_dims(x, -2)
return super().fit(x, y, **kwargs)
def predict(self, x, **kwargs):
x = np.expand_dims(x, -2)
return super().predict(x, **kwargs)
model = MyKerasRegressor(build_fn = model_base_LSTM, epochs=100, batch_size =70)