Python 在for循环中创建多个对象
我想在for循环中创建多个对象。我的代码如下:Python 在for循环中创建多个对象,python,keras,lstm,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 =
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.
您必须首先创建对象,然后添加到列表中 然后迭代它们以添加细节
lst = [x.Sequential() for x in range(20)]
for i in lst:
i.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 6)))
i.add(Dropout(0.2))
可以创建对象列表。 例如:
regressor_list = []
for x in range(0,20):
regressor = Sequential()
regressor_list.append(regressor)
现在对于e.x.您可以访问第五个回归器对象,如回归器_列表[5]。
希望这对你有所帮助:)难看的一行如下
layer_str = "Sequential().add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 6))).add(Dropout(0.2))"
models_lst = [eval(layer_str) for i in range(1,21)]
注:我建议使用其他答案。但是,我只是想表明,这也可以通过这种方式实现