【问题标题】:Multiple regression, reshaping inputs with multiple independent variables多元回归,用多个自变量重塑输入
【发布时间】:2021-10-08 16:48:15
【问题描述】:

我正在对我的数据进行多重回归,但绘制数据会引发错误:ValueError: x and y must be the same size

x.shape is (10000, 2) 
#Since I have two independent  x = dataset[['green', 'blue']]

y.shape is (10000,)

如何重塑数组?因为我在 x 中有两个自变量。

代码:

dataset = pd.read_csv('colors.csv')


x = dataset[['green', 'blue']] #independent variable
y = dataset['value']


x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 100)


mlr = LinearRegression()
mlr.fit(x_train, y_train)


print("Intercept: ", mlr.intercept_)
print("Coefficients:")
list(zip(x, mlr.coef_))

#Prediction of test set
y_pred_mlr= mlr.predict(x_test)
#Predicted values
print ("input test set", x_test)
print("Prediction for test set: {}".format(y_pred_mlr))

mlr_diff = pd.DataFrame({'Actual value': y_test, 'Predicted value': y_pred_mlr})


plt.scatter(x_train, y_train,color='g')
plt.plot(x_train, mlr.predict(x_train),color='k')

plt.show()

谢谢

【问题讨论】:

    标签: python numpy matplotlib scikit-learn regression


    【解决方案1】:

    问题是您使用的散点图需要两个一维数组(对于xy 轴)。

    您可以通过以下方式解决此问题:

    • 使用 3-D 绘图

       ax = plt.axes(projection='3d')
       ax.scatter3D(X_train[:,0], X_train[:,1], y_pred)
      
    • 针对y_pred为每个特征创建二维图

       fig, axs = plt.subplots(2)
       for i in range(X_train.shape[1]):
           axs[i].scatter(X_train[:,i], y_pred)
      

    【讨论】:

      【解决方案2】:

      对于这个问题,您需要将每个维度分散在一个图中。

      也许这段代码对你有帮助:

      color = ['g','b']
      plot_number = 1
      fig = plt.figure(figsize = (15,5))
      for i in range(x_train.shape[1]):
          ax, plot_number = fig.add_subplot(1, 2, plot_number), plot_number+1
          ax.scatter(x_train.iloc[:,i], y_train, color=color[i])
          ax.set_xlabel("x_train", fontsize = 18)
          ax.set_ylabel("Y", rotation = 0, fontsize = 18)
      plt.show()
      

      输出如下:

      【讨论】:

        猜你喜欢
        • 2012-04-20
        • 2019-05-19
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 2013-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多