对于该场景,您希望将这些序列中的每一个合并成一个更大的序列,其中包含所有股票的数据并将用于训练。
您可以将创建的 TimeSeriesGenerators追加到 Python 列表中。
stock_timegenerators = []
for stock in stocks:
stock_df = stock.copy()
features = stock_df.pop('symbol')
target = stock_df.pop('price')
x = np.array(stock_df.values)
y = np.array(target.values)
# sequence = TimeseriesGenerator(x, y, length = 4, sampling_rate = 1, batch_size = 1)
stock_timegenerators.append(TimeseriesGenerator(x, y, length = 4, sampling_rate = 1, batch_size = 1))
此输出将是一个附加的 TimeSeriesGenerator,您可以通过 迭代 列表 或 reference 来使用它按索引。
[<tensorflow.python.keras.preprocessing.sequence.TimeseriesGenerator at 0x7eff62c699b0>,
<tensorflow.python.keras.preprocessing.sequence.TimeseriesGenerator at 0x7eff62c6eba8>,
<tensorflow.python.keras.preprocessing.sequence.TimeseriesGenerator at 0x7eff62c782e8>]
同时拥有多个 Keras 时间序列意味着您正在为每只股票训练 多个 LSTM 模型。
您还可以使用这种方法有效地处理多个模型。
lstm_models = []
for time_series_gen in stock_timegenerators:
# lstm_models.append(create_model()) : You could create everything using functions
# Or in the loop like this.
model = Sequential()
model.add(LSTM(32, input_shape = (n_input, n_features)))
model.add(Dense(1))
model.compile(loss ='mse', optimizer = 'adam')
model.fit(time_series_gen, steps_per_epoch= 1, epochs = 5)
lstm_models.append(model)
这将输出一个附加的模型列表,并使用索引轻松引用。
[<tensorflow.python.keras.engine.sequential.Sequential at 0x7eff62c7b748>,
<tensorflow.python.keras.engine.sequential.Sequential at 0x7eff6100e160>,
<tensorflow.python.keras.engine.sequential.Sequential at 0x7eff63dc94a8>]
通过这种方式,您可以为不同的股票创建多个具有不同时间序列生成器的 LSTM 模型。
希望对你有所帮助。