numpy ValueError:形状为(291,1)的不可广播输出操作数与广播形状(291,6)不匹配

eqoofvh9  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(91)

我正在创建一个LSTM模型来预测一个月内特定时间的流量。然后我想在时间序列图上显示预测与真实结果。
我创建了一个df框架。该框架将有6个标签特征和1个目标值,称为Total。这将表示体积。我将我的嵌套框架分成两个不同的数组,其中X表示标签特征,Y表示目标值,如下所示:

X = df.drop(['Total', 'Date'], axis=1)
X = np.array(X)
Y = df['Total']
Y = np.array(Y)

X和Y的形状分别为(1452, 6)(1452,)。然后我使用MinMaxScaler()函数缩放每个数组。这会将每个值缩放为0和1之间的数字。我使用的代码是:

scaler = MinMaxScaler()

scale_Y = scaler.fit_transform(Y.reshape(-1, 1))
scale_Y = scale_Y.reshape(-1)
scale_X = scaler.fit_transform(X)

然后,我重新塑造了scale_Y,给予一个形状为(n_samples, )的一维数组。这些数据将分为80%用于训练,20%用于测试。这是通过以下方式实现的:

X_train, X_test, y_train, y_test = train_test_split(scale_X, scale_Y, test_size=0.2, random_state=42)

X_train数组被重新整形为(n_samples, sequence_length, n_features)的形式。这在下面的代码中显示:

n_training_samples = len(X_train)
n_test_samples = len(X_test)
sequence_length = 1
n_features = X_train.shape[1]

training_batch_size = n_training_samples - sequence_length +1
test_batch_size = n_test_samples - sequence_length +1
n_samples_reshaped = n_training_samples // sequence_length
reshaped_data = X_train[:n_samples_reshaped * sequence_length].reshape((n_samples_reshaped, sequence_length, n_features))

X_test_reshaped = X_test.reshape(X_test.shape[0], 1, X_test.shape[1])

然后将输入置于:

model = Sequential()
model.add(LSTM(units=48, activation='tanh', input_shape=(sequence_length, n_features), return_sequences=True))
model.add(LSTM(units=24, activation= 'tanh', return_sequences=True, name="Hidden_layer_1"))
model.add(LSTM(units=24, name="Hidden_layer_2"))
model.add(Dropout(0.2, name="Dropout_layer"))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(reshaped_data, y_train, epochs=500, batch_size=20)
y_pred = model.predict(X_test_reshaped)

模型训练和测试完成后,我想绘制时间序列图,显示预测结果与实际结果。为了尝试做到这一点,我尝试使用inverse_transform()函数,以便可以将数据放回其原始比例。我使用的代码是:

y_test_original_scale = scaler.inverse_transform(y_test)

这给了我一个错误消息说:Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.。所以我试着:

y_test_original_scale = scaler.inverse_transform(y_test.reshape(-1, 1))

这给了我一个错误消息说:
ValueError:形状为(291,1)的不可广播输出操作数与广播形状(291,6)不匹配
我是机器学习的新手,非常感谢你能帮助我纠正这个错误。谢谢

hgncfbus

hgncfbus1#

最后一次使用缩放器对象进行的拟合是在x值上

scale_X = scaler.fit_transform(X)

所以当你去做逆变换时,它被视为x值。
尝试创建两个不同的标量,例如

scaler_x = MinMaxScaler()
scaler_y = MinMaxScaler()

然后分别安装。你现在也可以在上层建筑上应用每一个的逆变换。

相关问题