值错误操作数在使用时无法与形状一起广播反变换在Python中

2024-04-19 12:04:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在代码的最后一部分,遇到一个操作数无法与shapes(69331,4)(3,)(69331,4)一起广播的问题。你知道吗

values = df.values 

## full data without resampling
#values = df.values

# integer encode direction
# ensure all data is float
#values = values.astype('float32')
# normalize features
scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(values)
# frame as supervised learning
reframed = series_to_supervised(scaled, 1, 1)

# drop columns we don't want to predict
reframed.drop(reframed.columns[[0]], axis=1, inplace=True)
print(reframed.head())

以下是我如何分割数据:

# split into train and test sets
values = reframed.values
n_train_time = 29713
train = values[:n_train_time, :]
test = values[n_train_time:, :]
##test = values[n_train_time:n_test_time, :]
# split into input and outputs
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape) 
# We reshaped the input into the 3D format as expected by LSTMs, namely [samples, timesteps, features].

以下是我制作模型的方法:

model = Sequential()
model.add(LSTM(100, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dropout(0.2))
#    model.add(LSTM(70))
#    model.add(Dropout(0.3))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')

以下是我如何适应我的人际网络:

history = model.fit(train_X, train_y, epochs=20, batch_size=70, validation_data=(test_X, test_y), verbose=2, shuffle=False)

以下是我的预测:

# make a prediction
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], 4))
# invert scaling for forecast
inv_yhat = np.concatenate((yhat, test_X[:,-3:]), axis=1)

这里是我的错误发生的地方:

inv_yhat = scaler.inverse_transform(inv_yhat)

错误是:

ValueError: operands could not be broadcast together with shapes (69331,4) (3,) (69331,4)

如果我这样做了:

print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

我得到:

(29713, 1, 4) (29713,) (69331, 4) (69331, 1)

任何帮助都将不胜感激


Tags: totestaddinputdatamodeltimetrain