线性回归

问题描述 投票:-1回答:1

我的问题陈述是:以下数据集显示了最近进行的关于驾驶时间与发生急性背痛风险的相关性的研究结果。找到此数据的最佳拟合线的等式。

数据集如下:

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

机器规格:Linux Ubuntu 18.10 64bit

我有一些错误:

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()
matplotlib linear-regression
1个回答
1
投票

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

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

但进一步下来,你重新定义(并因此覆盖)它

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

这导致错误,因为这最后一个y是一个字符串,而不是一个像X这样的8个元素的数组(和你最初的y一样)。

用其他东西改变它,例如Y,最后在相关的路线:

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

为了保持你的y最初定义,你应该没事。

© www.soinside.com 2019 - 2024. All rights reserved.