多变量时间序列的递归神经网络 - TensorFlow

Recurrent neural networks for Time Series with Multiple Variables - TensorFlow

我使用以前的需求来预测未来的需求,使用 3 variables,但是每当我 运行 我的代码 Y axis 显示错误

如果我在 Y axis 上单独使用一个变量,它没有错误。

示例:

demandaY = bike_data[['cnt']]
n_steps = 20

for time_step in range(1, n_steps+1):
    demandaY['cnt'+str(time_step)] = demandaY[['cnt']].shift(-time_step).values

y = demandaY.iloc[:, 1:].values
y = np.reshape(y, (y.shape[0], n_steps, 1))

数据集

脚本

features = ['cnt','temp','hum']
demanda = bike_data[features]
n_steps = 20

for var_col in features:
    for time_step in range(1, n_steps+1):
        demanda[var_col+str(time_step)] = demanda[[var_col]].shift(-time_step).values

demanda.dropna(inplace=True)
demanda.head()

n_var = len(features)
columns = list(filter(lambda col: not(col.endswith("%d" % n_steps)), demanda.columns))

X = demanda[columns].iloc[:, :(n_steps*n_var)].values
X = np.reshape(X, (X.shape[0], n_steps, n_var))

y = demanda.iloc[:, 0].values
y = np.reshape(y, (y.shape[0], n_steps, 1))

输出

ValueError: cannot reshape array of size 17379 into shape (17379,20,1)

GitHub: repository

不清楚 OP 是否仍然想要答案,但我会 post 我在评论中链接的答案稍作修改。

时间序列数据集可以有不同的类型,让我们考虑一个数据集,它具有 X 作为特征和 Y 作为标签。根据问题的不同,Y 可能是来自 X 的样本在时间上发生了偏移,也可能是您要预测的另一个目标变量。

def create_dataset(X,Y, look_back=10, label_lag = -1, stride = 1):

    dataX, dataY = [], []

    for i in range(0,(len(X)-look_back + 1),stride):
        a = X[i:(i+look_back)]
        dataX.append(a)
        b = Y[i + look_back + label_lag]
        dataY.append(b)
    return np.array(dataX), np.array(dataY)

print(features.values.shape,labels.shape)
#(619,4), (619,1)

x,y = create_dataset(X=features.values,Y=labels.values,look_back=10,stride=1)
(x.shape,y.shape)
#(610, 10, 4), (610, 1)

其他参数的使用:

  1. label_lag :如果 X 个样本在时间 tY 个样本将在时间 t+label_lag。默认值会将 XY 放在同一索引 t 中。

XY 的第一个样本的索引:

if label_lag is -1:
np.where(x[1,-1]==features.values)[0],np.where(y[1] == labels.values)[0]
#(10,10,10,10), (10)

if label_lag is 0:
np.where(x[1,-1]==features.values)[0],np.where(y[1] == labels.values)[0]
#(10,10,10,10), (11)
  1. look_back:这是您当前时间步 t 中数据集过去历史的样本数。 look_back of 10 表示在一个样本中将有来自 t-10 to t 的样本。

  2. stride :两个连续样本之间的索引差距。当 stride=2 时,如果 X 的第一个样本包含来自索引 0 to 10 的行,那么第二个样本将包含来自索引 2 to 12 的行。

此外,您还可以根据您当前的问题在Y中进行回顾,Y也可以是多维的。在那种情况下,变化只是这个 b=Y[i:(i+look_back+label_lag)]

keras 中的 TimeseriesGenerator 可以实现相同的功能。

TimeseriesGenerator(features.values,labels.values,length=10,batch_size=64,stride=1)

其中 lengthlook_back 相同。默认情况下,featureslabels 之间存在 1 的差距,即 X 中的样本将来自 t-10 to t,而 Y 中的相应样本将位于指数 t+1。如果您希望两者都具有相同的索引,则只需 shift 在传入生成器之前将标签加一个。