使用时间戳在python中构建神经网络时无法将输入数组从形状(2,3)广播到形状(3)

数据挖掘 Python 神经网络
2022-03-08 23:17:47

在这里,我希望每 60 分钟预测一次值。所以我有三个输入的数据 540。所以我写了一个带有时间步骤的代码,它给了我这个错误。谁能帮我解决这个问题?

我的代码:

y=data['y1'].astype(int)
cols=['x1', 'x2', 'x3']
x=data[cols].astype(int)
n = x.shape[0]
p = x.shape[1]
x  = x.values
y = y.values
train_start = 0
train_end = int(np.floor(0.8*n))
test_start = train_end+1 
test_end = n
x_train = x[np.arange(train_start, train_end), :]
x_test = x[np.arange(test_start, test_end), :]
y_train = y[np.arange(train_start, train_end), :]
y_test = y[np.arange(test_start, test_end), :]
x_train=x_train.reshape(x_train.shape +(1,))
x_test=x_test.reshape(x_test.shape + (1,))

num_time_steps = 9
num_features = x.shape[1]

x_train = np.zeros((x_train.shape[0] - num_time_steps + 1, num_time_steps, num_features), dtype="float32")
x_test = np.zeros((x_test.shape[0] - num_time_steps + 1, num_time_steps, num_features), dtype="float32")

for i in range(len(x_train)):
for timestep in range(num_time_steps):
    x_train[i][timestep] = x_train[i + timestep]

for i in range(len(x_test)):
for timestep in range(num_time_steps):
    x_test[i][timestep] = x_test[i + timestep]

 y_train = y_train[num_time_steps - 1:]
 y_test = y_test[num_time_steps - 1:]

在此处输入图像描述

在此处输入图像描述

更改代码:

train_end = 80
x_train=x[0: train_end ,]
x_test=x[train_end +1: ,]
y_train=y[0: train_end]
y_test=y[train_end +1:] 
x_train=x_train.reshape(x_train.shape +(1,))
x_test=x_test.reshape(x_test.shape + (1,))
num_time_steps = 9
num_features = x.shape[1]
x_train_n = np.zeros((x_train.shape[0] - num_time_steps + 1, num_time_steps, num_features), dtype="float32")
x_test_n = np.zeros((x_test.shape[0] - num_time_steps + 1, num_time_steps, num_features), dtype="float32")
for i in range(len(x_train_n)):
for timestep in range(num_time_steps):
    x_train_n[i][timestep] = x_train[i + timestep]
for i in range(len(x_test_n)):
for timestep in range(num_time_steps):
    x_test_n[i][timestep] = x_test[i+timestep]
y_train_n = y_train[num_time_steps - 1:]
y_test_n = y_test[num_time_steps - 1:]

错误, 在此处输入图像描述

1个回答

首先,您应该为 3D 和 2D 使用单独的变量x_train

x_train_n = np.zeros((x_train.shape[0] - num_time_steps + 1, num_time_steps, num_features), dtype="float32")
x_test_n = np.zeros((x_test.shape[0] - num_time_steps + 1, num_time_steps, num_features), dtype="float32")

而且,你的外循环应该跨越 x_train的,即x_train_n

for i in range(len(x_train_n)):
   for timestep in range(num_time_steps):
       x_train_n[i][timestep] = x_train[i + timestep].squeeze()

也更改另一个循环(用于测试用例的循环)。