【问题标题】:Numpy ValueError: operands could not be broadcast together with shapes (148912,8) (6,) (148912,8)Numpy ValueError:操作数无法与形状一起广播 (148912,8) (6,) (148912,8)
【发布时间】:2021-06-14 06:11:38
【问题描述】:

在进行预测后尝试反转比例时,我一直遇到给定的错误。

我当前的代码如下所示:

from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
 
# convert series to supervised learning
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = DataFrame(data)
    cols, names = list(), list()
    # input sequence (t-n, ... t-1)
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
    # forecast sequence (t, t+1, ... t+n)
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
    # put it all together
    agg = concat(cols, axis=1)
    agg.columns = names
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg
 
# load dataset
dataset = read_csv('../input/test-jetson/test.csv', header=0, parse_dates=['Timestamp'])
values = dataset#.values
# integer encode direction
#encoder = LabelEncoder()
#values[:,4] = encoder.fit_transform(values[:,4])
# ensure all data is float
values['Timestamp'] = values["Timestamp"].values.astype('float32')
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[[9,10,11]], axis=1, inplace=True)#,12,13,14,15
print(reframed.head())
 
# split into train and test sets
values = reframed.values
n_train_hours = 365 * 24
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]
# 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)
# design network
model = Sequential()
model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# fit network
history = model.fit(train_X, train_y, epochs=50, batch_size=72, validation_data=(test_X, test_y), verbose=2, shuffle=False) #batch_size = 72
# plot history
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='test')
pyplot.legend()
pyplot.show()
 
# make a prediction
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))
# invert scaling for forecast
inv_yhat = concatenate((yhat, test_X[:, 1:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
inv_yhat = inv_yhat[:,0]
# invert scaling for actual
test_y = test_y.reshape((len(test_y), 1))
inv_y = concatenate((test_y, test_X[:, 1:]), axis=1)
inv_y = scaler.inverse_transform(inv_y)
inv_y = inv_y[:,0]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)

错误发生在inv_yhat = scaler.inverse_transform(inv_yhat)这一行

我的数据集由 6 列组成,第一列是日期时间格式的时间戳,另外 5 列是整数; 157673 行。

我正在尝试进行时间序列预测,以防有助于澄清。

【问题讨论】:

  • 代码中的哪一行给出了这个错误?
  • @ShubhamPanchal 91 号线:inv_yhat = scaler.inverse_transform(inv_yhat)

标签: python pandas numpy tensorflow keras


【解决方案1】:

问题在于 numpy 数组形状。在对数组执行任何数学运算时,所有数组都应具有相同的形状。 在这种情况下,numpy_arrays 具有不同的形状 (148912,8) (6,) (148912,8) 它应该是这样的 (148912,8) (6,1) (148912,8)

x = np.array(x)
x = np.expand_dims(x, axis=-1)

【讨论】:

    猜你喜欢
    • 2012-08-05
    • 2020-06-20
    • 2014-08-24
    • 2017-09-09
    • 2012-10-31
    • 2013-04-07
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多