首页 > 解决方案 > 处理 Bagging 方法时如何修复 TypeError: +: 'int' 和 'NoneType' 的不支持的操作数类型

问题描述

我需要对 LSTM 使用 Bagging 方法,对时间序列数据进行训练。我已经定义了模型库并使用 KerasRegressor 链接到 scikit-learn。但是有 AttributeError: 'KerasRegressor' 对象没有属性 'loss'。我该如何解决?

更新:我使用了 Manoj Mohan 的方法(在第一条评论中)并在适合的步骤中成功。但是,当我将 Manoj Mohan 的类修改为

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'

标签: keraslstm

解决方案


方法有错误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)

推荐阅读