首页 > 解决方案 > ValueError:无法将输入数组从形状 (90742,1) 广播到形状 (240742,1)

问题描述

我遇到过一个ValueError: could not broadcast input array from shape (90742,1) into shape (240742,1).

这是我的代码:

# shift train predictions for plotting 
train_predict_plot = np.empty_like(data)
train_predict_plot[:, :] np.nan
train_predict_plot[lags:len(train_predict)+lags, :] = train_predict

# shift test predictions for plotting
test_predict_plot = np.empty_like(data)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict) + (lags * 2)+1:len(data)-1, :] = test_predict

# plot observation and predictions 
plt.plot(data, label='Observed', color='#006699'); 
plt.plot(train_predict_plot, label='Prediction for Train Set', color='#006699', alpha=0.5); 
plt.plot(test_predict_plot, label='Prediction for Test Set', color='#ff0066'); 
plt.legend(loc='upper left') 
plt.title('LSTM Recurrent Neural Net') 
plt.show()

这是错误:

值错误

我看过前面的问题,但它们都是不同的。有人能告诉我如何在我的情况下专门解决这个问题吗?非常感谢。

标签: pythontime-serieslstm

解决方案


因此,您test_predict.shape必须是(90742,1)由于test_predict_plot[240742,:]=test_predict此处输入而面临的错误。

形状test_predict_plot[75003:315745,:]变为(240742,1)并输入比这更短或不同形状的数组将引发错误。

我试图通过运行您在链接中提供的代码来重现错误,但没有错误: len(train_predict)=116len(data)=144并且len(test_predict)=20与代码的计算非常吻合。通过计算,我的意思是在这行代码中:

    test_predict_plot[len(train_predict)+(lags*2)+1:len(data)-1, :] = test_predict

这将成为:

    test_predict_plot[116+6+1:144-1, :] = test_predict 

因此,您需要对代码进行更改,以使输入的长度匹配。您也可以通过以下代码更改来尝试:

    test_predict_plot[<len(test_predict)>, :] = test_predict

解决方案

发现问题:

    train = dataset[150000:225000, :]
    test = dataset[225000:, :]

您需要在此处进行更改:

    train_predict_plot = np.empty_like(data[150000:, :])
    train_predict_plot[:, :] = np.nan
    train_predict_plot[lags: len(train_predict) + lags, :] = train_predict

    # shift test predictions for plotting
    test_predict_plot = np.empty_like(data[150000:, :])
    test_predict_plot[:, :] = np.nan
    test_predict_plot[len(train_predict)+(lags*2)+1:len(data[150000:, :])-1, :] = test_predict

推荐阅读