初识线性回归

本文介绍了如何使用Excel进行线性回归分析,包括设置Excel加载项和使用数据分析工具。接着,通过jupyter notebook探讨了使用最小二乘法手动实现线性回归,并进一步利用sklearn库进行线性回归的便捷操作。

一、Excel完成线性回归

  • 首先在文件中选择选项,再选择加载项,将管理处修改为Excel加载项,最后选择转到。

  • 选择分析工具库和分析工具库-VBA勾选上接着选择确定。
    在这里插入图片描述

  • 在数据选项中选择 数据分析
    在这里插入图片描述

  • 选择回归,再选择y值x值区域
    在这里插入图片描述
    在这里插入图片描述

  • 先选择前20组数据得到结果
    在这里插入图片描述

  • 200组数据
    在这里插入图片描述

  • 2000组数据
    在这里插入图片描述

二、jupyter编程使用最小二乘法

  • 代码
#用jupyter编程(不借助第三方库),用最小二乘法,
#当体重X变量取20个的时候
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
points = np.genfromtxt("D:/weights_heights(身高-体重数据集).xls",delimiter=",")
#points
#提取points中的两列数据,分别作为x,y
# 回归方程y = ax + b           求a 和 b
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(f'回归线方程:y = {a}x + {b}') 
y1 = a*x + b
plt.scatter(x,y)
plt.plot(x,y1,c='r')


在这里插入图片描述

三、jupyter编程,借助skleran

  • 代码
import pandas as pd
import numpy as np
from numpy import array
from sklearn import linear_model
import matplotlib.pyplot as plt
import math
d=pd.read_excel('weights_heights.xlsx')
d.shape
#20个
x1 = array(d[['Height']].values[:20,:])
y1 = array(d[['Weight']].values[:20,:])
model = linear_model.LinearRegression()
model.fit(x1,y1)
#斜率
print(model.coef_)
#截距
print(model.intercept_)
a=model.intercept_
b=model.coef_
y_hate1=b*x1+a
print("线性回归方程为:y1=",b,"x1",a)
#计算R^2
model.score(x1,y1)
plt.figure()
plt.scatter(x1,y1)#散点图绘制初始数据
plt.plot(x1,y_hate1,color='r')#绘制直线
plt.show()

在这里插入图片描述

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值