一、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()


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

被折叠的 条评论
为什么被折叠?



