线性回归:ValueError:x和y必须具有相同的第一维度,但具有形状(10,1)和(1,1)

2024-09-27 17:42:47 发布

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

我还是pyhton的新手,我试着显示线性回归图,但出现了一些错误

代码如下:

 linear_regression = lm.LinearRegression()
 linear_x = data.Luas.values.reshape(-1,1)
 linear_y = data.Harga.values.reshape(-1,1)
 linear_regression.fit(linear_x,linear_y)
 print("Intercept = ",linear_regression.intercept_)
 print("Coefisien = ",linear_regression.coef_)
 print("Persamaan menggunakan fungsi Linear Regression :")
 print("Y=",linear_regression.intercept_,"+",linear_regression.coef_,"X")
 print("Prediksi Luas Tanah (X) = 1800")
 print("Maka:")
 result = linear_regression.predict([[1800]])
 print("Harga Tanah(Y) = ",result,"jt")


 plt.scatter(linear_x,linear_y,color='black')
 plt.plot(linear_x,linear_regression.predict([[1800]]),color='blue')
 plt.title('Luas Tanah/Area VS Harga/Price')
 plt.ylabel('Harga Tanah/Price (jt)')
 plt.xlabel('Luas Tanah/Area')
 plt.show()

错误:

Traceback (most recent call last):
 File "D:/Tugas/smt6/data mining/tugasKlasifikasi/klasifikasi.py", line 55, in <module>
  plt.plot(linear_x,linear_regression.predict([[1800]]),color='blue')
 File "C:\Users\Thor\Anaconda3\envs\coba\lib\site-packages\matplotlib\pyplot.py", line 2796, in 
  plot is not None else {}), **kwargs)
 File "C:\Users\Thor\Anaconda3\envs\coba\lib\site-packages\matplotlib\axes\_axes.py", line 1665, 
  in plot lines = [*self._get_lines(*args, data=data, **kwargs)]
 File "C:\Users\Thor\Anaconda3\envs\coba\lib\site-packages\matplotlib\axes\_base.py", line 225, 
  in __call__yield from self._plot_args(this, kwargs)
 File "C:\Users\Thor\Anaconda3\envs\coba\lib\site-packages\matplotlib\axes\_base.py", line 391, 
  in _plot_args x, y = self._xy_from_xy(x, y)
 File "C:\Users\Thor\Anaconda3\envs\coba\lib\site-packages\matplotlib\axes\_base.py", line 270, 
  in _xy_from_xy "have shapes {} and {}".format(x.shape, y.shape))
 ValueError: x and y must have same first dimension, but have shapes (10, 1) and (1, 1)

非常感谢你的帮助


Tags: inpydataplotlinepltusersfile
1条回答
网友
1楼 · 发布于 2024-09-27 17:42:47

你的问题与线性回归无关。当您要打印时,它会出现:

plt.plot(linear_x,linear_regression.predict([[1800]]),color='blue')

问题是linear_x有形状(10, 1),而你的prediction有形状(1, 1)。所以你不能这么做。它们必须提供相同的第一个形状

相关问题 更多 >

    热门问题