数据分析的那些事

数据分析02 - 线性回归

2019-10-12  本文已影响0人  数据社

可分为线性回归分析和非线性回归分析。如果在回归分析中,只包括一个自变量和一个因变量,且二者的关系可用一条直线近似表示,这种回归分析称为一元线性回归分析。如果回归分析中包括两个或两个以上的自变量,且因变量和自变量之间是线性关系,则称为多元线性回归分析。

Python sklearn中的LinearRegreesion实例:

import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt

# 读入CSV数据
csv_data = pd.read_csv('E:\pycode\data\md0301.csv').dropna() #过滤空值
print(csv_data.shape)
print(csv_data.all)

# 建立线性回归模型
regr = linear_model.LinearRegression()
# 拟合
regr.fit(csv_data['m_motor_rotate'].values.reshape(-1, 1), csv_data['vehicle_speed']) # 注意此处.reshape(-1, 1),因为X是一维的!
#得到线性回归公式的系数y=ax+b
a=regr.coef_
print(len(a))
b=regr.intercept_
print(b)

print(regr.score(csv_data['m_motor_rotate'].values.reshape(-1, 1), csv_data['vehicle_speed']))
# 1.真实的点
plt.scatter(csv_data['m_motor_rotate'], csv_data['vehicle_speed'], color='black')
# 2.拟合的直线
plt.plot(csv_data['m_motor_rotate'], regr.predict(csv_data['m_motor_rotate'].values.reshape(-1,1)), color='red', linewidth=1)

plt.show()

运行如下:


线性回归
上一篇 下一篇

猜你喜欢

热点阅读