python - 在 for 循环中创建多个对象

标签 python keras lstm

我想在 for 循环中创建多个对象。我的代码是这样的:

regressor1 = Sequential()

# Adding the first LSTM layer and some Dropout regularisation
regressor1.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 6)))
regressor1.add(Dropout(0.2))

regressor2 = Sequential()

# Adding the first LSTM layer and some Dropout regularisation
regressor2.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 6)))
regressor2.add(Dropout(0.2))

.
.
.

regressor20 = Sequential()

# Adding the first LSTM layer and some Dropout regularisation
regressor20.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 6)))
regressor20.add(Dropout(0.2))

我如何在 for 循环中执行此操作?

感谢您的帮助。

最佳答案

模型没有什么特别之处,它们是对象,因此您可以在循环中创建模型对象(回归器)列表:

regressors = list()
for _ in range(20):
  model = Sequential()
  model.add(LSTM(units=50, ...))
  model.add(Dropout(0.2))
  regressors.append(model)
# Now access like you would any array
# regressors[0] etc will give you models.

关于python - 在 for 循环中创建多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51477729/

相关文章:

python - 使用 selenium 在新选项卡中打开链接时出错

python - Djoser 用户激活电子邮件 POST 示例

python - 在不关闭 Python 中的 Selenium Webdriver session 的情况下捕获 `KeyboardInterrupt`

python - 预测方法为创建的模型给出错误

machine-learning - 在 Keras 中使用 LSTM 将一系列向量映射到单个向量

pip 包的 Python 目录不起作用

python - 如何在 Keras 中获得预测值?

python - Tensorflow Keras 指标未显示

python - tf.keras.layers 和 tf.layers 有什么区别?

python-3.x - 使用 LSTM 在在线多类分类中的每次迭代中预测给出相同的值