<p>下面是一个设置时间序列数据以训练LSTM的示例。模型输出是毫无意义的,因为我只是设置它来演示如何构建模型。</p>
<pre><code>import pandas as pd
import numpy as np
# Get some time series data
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/timeseries.csv")
df.head()
</code></pre>
<p>时间序列数据帧:</p>
<pre><code>Date A B C D E F G
0 2008-03-18 24.68 164.93 114.73 26.27 19.21 28.87 63.44
1 2008-03-19 24.18 164.89 114.75 26.22 19.07 27.76 59.98
2 2008-03-20 23.99 164.63 115.04 25.78 19.01 27.04 59.61
3 2008-03-25 24.14 163.92 114.85 27.41 19.61 27.84 59.41
4 2008-03-26 24.44 163.45 114.84 26.86 19.53 28.02 60.09
</code></pre>
<p>您可以将输入构建为向量,然后使用pandas<code>.cumsum()</code>函数构建时间序列的序列:</p>
<pre><code># Put your inputs into a single list
df['single_input_vector'] = df[input_cols].apply(tuple, axis=1).apply(list)
# Double-encapsulate list so that you can sum it in the next step and keep time steps as separate elements
df['single_input_vector'] = df.single_input_vector.apply(lambda x: [list(x)])
# Use .cumsum() to include previous row vectors in the current row list of vectors
df['cumulative_input_vectors'] = df.single_input_vector.cumsum()
</code></pre>
<p>可以以类似的方式设置输出,但它将是单个矢量而不是序列:</p>
<pre><code># If your output is multi-dimensional, you need to capture those dimensions in one object
# If your output is a single dimension, this step may be unnecessary
df['output_vector'] = df[output_cols].apply(tuple, axis=1).apply(list)
</code></pre>
<p>输入序列的长度必须相同才能在模型中运行,因此需要将它们填充为累积向量的最大长度:</p>
<pre><code># Pad your sequences so they are the same length
from keras.preprocessing.sequence import pad_sequences
max_sequence_length = df.cumulative_input_vectors.apply(len).max()
# Save it as a list
padded_sequences = pad_sequences(df.cumulative_input_vectors.tolist(), max_sequence_length).tolist()
df['padded_input_vectors'] = pd.Series(padded_sequences).apply(np.asarray)
</code></pre>
<p>训练数据可以从数据帧中提取并放入numpy数组中。<strong>请注意,从数据帧中输出的输入数据不会构成三维数组。它生成一个数组,这是不同的。</strong></p>
<p>可以使用hstack和reforme来构建三维输入数组。</p>
<pre><code># Extract your training data
X_train_init = np.asarray(df.padded_input_vectors)
# Use hstack to and reshape to make the inputs a 3d vector
X_train = np.hstack(X_train_init).reshape(len(df),max_sequence_length,len(input_cols))
y_train = np.hstack(np.asarray(df.output_vector)).reshape(len(df),len(output_cols))
</code></pre>
<p>为了证明这一点:</p>
<pre><code>>>> print(X_train_init.shape)
(11,)
>>> print(X_train.shape)
(11, 11, 6)
>>> print(X_train == X_train_init)
False
</code></pre>
<p>一旦有了训练数据,就可以定义输入层和输出层的维度。</p>
<pre><code># Get your input dimensions
# Input length is the length for one input sequence (i.e. the number of rows for your sample)
# Input dim is the number of dimensions in one input vector (i.e. number of input columns)
input_length = X_train.shape[1]
input_dim = X_train.shape[2]
# Output dimensions is the shape of a single output vector
# In this case it's just 1, but it could be more
output_dim = len(y_train[0])
</code></pre>
<p>建立模型:</p>
<pre><code>from keras.models import Model, Sequential
from keras.layers import LSTM, Dense
# Build the model
model = Sequential()
# I arbitrarily picked the output dimensions as 4
model.add(LSTM(4, input_dim = input_dim, input_length = input_length))
# The max output value is > 1 so relu is used as final activation.
model.add(Dense(output_dim, activation='relu'))
model.compile(loss='mean_squared_error',
optimizer='sgd',
metrics=['accuracy'])
</code></pre>
<p>最后,您可以培训模型并将培训日志保存为历史记录:</p>
<pre><code># Set batch_size to 7 to show that it doesn't have to be a factor or multiple of your sample size
history = model.fit(X_train, y_train,
batch_size=7, nb_epoch=3,
verbose = 1)
</code></pre>
<p>输出:</p>
<pre><code>Epoch 1/3
11/11 [==============================] - 0s - loss: 3498.5756 - acc: 0.0000e+00
Epoch 2/3
11/11 [==============================] - 0s - loss: 3498.5755 - acc: 0.0000e+00
Epoch 3/3
11/11 [==============================] - 0s - loss: 3498.5757 - acc: 0.0000e+00
</code></pre>
<p>就这样。使用<code>model.predict(X)</code>,其中<code>X</code>与<code>X_train</code>的格式相同(而不是样本数),以便从模型进行预测。</p>