栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

初识线性回归

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

初识线性回归

三种线性回归方式对比 一、EXCEL

①:选取20组数据:

回归方程为y=4.128x-152.23
R²=0.3254
②选取200组数据

回归方程为y=3.4317x-105.96
R²=0.31
③选取2000组数据

回归方程为y=2.9555x-73.661
R²=0.2483

二、用jupyter编程(最小二乘法)

代码:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
points = np.genfromtxt("F:/Python/mydata.csv",delimiter=",",encoding='utf-8')
x=points[0:20,1];
y=points[0:20,2];
x_mean = np.mean(x)
y_mean = np.mean(y)
xsize = x.size
zi = (x * y).sum() - xsize * x_mean *y_mean
mu = (x ** 2).sum() - xsize * x_mean ** 2
# 参数a b
a = zi / mu
b = y_mean - a * x_mean
# 这里对参数保留两位有效数字
a = np.around(a,decimals=2)
b = np.around(b,decimals=2)
print('Equation of linear regression: y = {a}x + {b}')
y1 = a*x + b
plt.scatter(x,y)
plt.plot(x,y1,c='r')


20(200、2000)数值直接替换
回归方程分别为:
20:y = 4.13x + -152.23
200:y = 3.43x + -105.96
2000: y = 2.96x + -73.66

三、用jupyter编程,借助skleran库

源代码:

#导入sklearn等各种包以及数据文件
import pandas as pd
import numpy as np
from numpy import array
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import math
df = pd.read_excel("D:/Python/mydata.xls")

#输出文件大小
df.shape

#20/200/2000组数据
x=array(df[['Height']].values[:20,:])
y=array(df[['Weight']].values[:20,:])

# x=array(df[['Height']].values[:200,:])
# y=array(df[['Weight']].values[:200,:])

# x=array(df[['Height']].values[:2000,:])
# y=array(df[['Weight']].values[:2000,:])

#导入线性回归函数
model = LinearRegression()
model.fit(x,y)

#斜率
a=model.coef_
print("斜率=",model.coef_)

#截距
b=model.intercept_
print("截距=",model.intercept_)

#输出线性回归方程
y_hat=a*x+b
print("线性回归方程:y=",a,"x",b)
print("R2=",model.score(x,y))

#绘图
plt.figure()
plt.scatter(x,y)
plt.plot(x,y_hat,color='r') #绘制直线
plt.show()

20:

200:

2000:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/283685.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号