线性回归

时间:2019-04-14 15:17:37

标签: matplotlib linear-regression

我的问题陈述是: 以下数据集显示了最近进行的有关驾驶所花费的小时数与发生急性背痛风险的相关性研究的结果。找到该数据的最佳拟合线方程。

数据集如下:

x   y
10  95
9   80
2   10
15  50
10  45
16  98
11  38
16  93

机器规格:Linux Ubuntu 18.10 64位

我遇到一些错误:

python LR.py
Accuracy :
43.70948145101002
[6.01607946]
Enter the no of hours10
y :
0.095271*10.000000+5.063367
Risk Score :  6.016079463451905
Traceback (most recent call last):
File "LR.py", line 30, in <module>
plt.plot(X,y,'o')
File "/home/sumeet/anaconda3/lib/python3.6/site- 
packages/matplotlib/pyplot.py", line 3358, in plot
ret = ax.plot(*args, **kwargs)
File "/home/sumeet/anaconda3/lib/python3.6/site- 
packages/matplotlib/__init__.py", line 1855, in inner
return func(ax, *args, **kwargs)
File "/home/sumeet/anaconda3/lib/python3.6/site- 
packages/matplotlib/axes/_axes.py", line 1527, in plot
for line in self._get_lines(*args, **kwargs):
File "/home/sumeet/anaconda3/lib/python3.6/site- 
packages/matplotlib/axes/_base.py", line 406, in _grab_next_args
for seg in self._plot_args(this, kwargs):
File "/home/sumeet/anaconda3/lib/python3.6/site- 
packages/matplotlib/axes/_base.py", line 383, in _plot_args
x, y = self._xy_from_xy(x, y)
File "/home/sumeet/anaconda3/lib/python3.6/site- 
packages/matplotlib/axes/_base.py", line 242, in _xy_from_xy
"have shapes {} and {}".format(x.shape, y.shape))
ValueError: x and y must have same first dimension, but have 
shapes (8, 1) and (1,)

代码如下:

import matplotlib.pyplot as plt
import pandas as pd

# Read Dataset
dataset=pd.read_csv("hours.csv")
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1].values

# Import the Linear Regression and Create object of it
from sklearn.linear_model import LinearRegression
regressor=LinearRegression()
regressor.fit(X,y)
Accuracy=regressor.score(X, y)*100
print("Accuracy :")
print(Accuracy)

# Predict the value using Regressor Object
y_pred=regressor.predict([[10]])
print(y_pred)

# Take user input
hours=int(input('Enter the no of hours'))

#calculate the value of y
eq=regressor.coef_*hours+regressor.intercept_
y='%f*%f+%f' %(regressor.coef_,hours,regressor.intercept_)
print("y :")
print(y)
print("Risk Score : ", eq[0])
plt.plot(X,y,'o')
plt.plot(X,regressor.predict(X));
plt.show()

1 个答案:

答案 0 :(得分:1)

在代码的开头,您定义了可能要绘制的y

y=dataset.iloc[:,1].values

但再往下,您将其重新定义(并覆盖)为

y='%f*%f+%f' %(regressor.coef_,hours,regressor.intercept_)

这会导致错误,因为最后一个y是一个字符串,而不是包含8个元素的数组,例如X(以及您的初始y)。

用其他方式更改它,例如Y,在最后的相关行:

Y='%f*%f+%f' %(regressor.coef_,hours,regressor.intercept_)
print("Y :")
print(Y)

以使您的y保持最初定义的状态,您应该没事。