简体   繁体   中英

Linear Regression : ValueError: x and y must have same first dimension, but have shapes (10, 1) and (1, 1)

Iam still newbie at pyhton, and i try to show the linear regression graph but got some error

this is the code :

 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()

the error :

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)

Thank you very much for helping!

Your problem is not connected with linear regression. It appears when you want to plot:

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

And the issue is that linear_x has shape (10, 1) and your prediction has shape (1, 1) . So you can not do that. They must provide the same first shape.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM