keras - 处理 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'
解决方案
方法有错误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)
推荐阅读
- python - 为什么我的两个参数的表达式值不正确?
- javascript - 制作宾果游戏。如何从一组中生成要显示的随机数,而不重复生成和显示哪个数字?
- javascript - RegExp 问号无法正常工作
- node.js - 用于节点 + 静态文件的 nginx 配置未捕获
- css - 如何制作 3d css 胶囊
- google-apps-script - 带有下拉输入的 Google Sheet 自定义对话框
- javascript - 在编译器实例上从 webpack 获取构建条目
- reactjs - 如何对 React 编译器执行 Null 检查
- mysql - 您可以索引数据库中具有相同列名的所有表中的列吗?
- go - 关闭 Go http.Client 的连接池