第2作业2
文章目录
前言
请先下载身高体重数据集(weights_heights.xls)。
https://mooc1.chaoxing.com/ueditorupload/read?objectId=36c330a6840f603c329b82d30c19f5d3&fileOriName=weights_heights(%E8%BA%AB%E9%AB%98-%E4%BD%93%E9%87%8D%E6%95%B0%E6%8D%AE%E9%9B%86).xls
一、excel中线性回归练习
由于电脑上没有预装offcie,此处用WPS来代替完成。
1、设置图表
用WPS打开下载的数据集。
点击图表工具、添加元素,对图标添加线性趋势线。
双击趋势线,设置属性。
双击横、纵坐标轴,设置范围。
右键点击图表,选中数据。
在$ $中修改行数,来选择任意组数据。
2、结果展示
(1)20组数据
(2)200组数据
(3)2000组数据
二、jupyter用最小二乘法重做第1题
首先将所需要的数据文件导入到jupyter中,就可以不用在程序里使用数据文件时加入路径。
打开jupyter,点击upload,选择你需要的文件。
新建一个python文档
1、20组数据
代码如下:
import pandas as pd
import numpy as np
import math
#准备数据
p=pd.read_excel('weights_heights(身高-体重数据集).xls','weights_heights')
#读取20行数据
p1=p.head(20)
x=p1["Height"]
y=p1["Weight"]
# 平均值
x_mean = np.mean(x)
y_mean = np.mean(y)
#x(或y)列的总数(即n)
xsize = x.size
zi=((x-x_mean)*(y-y_mean)).sum()
mu=((x-x_mean)*(x-x_mean)).sum()
n=((y-y_mean)*(y-y_mean)).sum()
# 参数a b
a = zi / mu
b = y_mean - a * x_mean
#相关系数R的平方
m=((zi/math.sqrt(mu*n))**2)
# 这里对参数保留4位有效数字
a = np.around(a,decimals=4)
b = np.around(b,decimals=4)
m = np.around(m,decimals=4)
print(f'回归线方程:y = {a}x +({b})')
print(f'相关回归系数为{m}')
#借助第三方库skleran画出拟合曲线
y1 = a*x + b
plt.scatter(x,y)
plt.plot(x,y1,c='r')
结果如下:
2、200组数据
代码如下:
import pandas as pd
import numpy as np
import math
#准备数据
p=pd.read_excel('weights_heights(身高-体重数据集).xls','weights_heights')
#读取200行数据
p1=p.head(200)
x=p1["Height"]
y=p1["Weight"]
# 平均值
x_mean = np.mean(x)
y_mean = np.mean(y)
#x(或y)列的总数(即n)
xsize = x.size
zi=((x-x_mean)*(y-y_mean)).sum()
mu=((x-x_mean)*(x-x_mean)).sum()
n=((y-y_mean)*(y-y_mean)).sum()
# 参数a b
a = zi / mu
b = y_mean - a * x_mean
#相关系数R的平方
m=((zi/math.sqrt(mu*n))**2)
# 这里对参数保留4位有效数字
a = np.around(a,decimals=4)
b = np.around(b,decimals=4)
m = np.around(m,decimals=4)
print(f'回归线方程:y = {a}x +({b})')
print(f'相关回归系数为{m}')
#借助第三方库skleran画出拟合曲线
y1 = a*x + b
plt.scatter(x,y)
plt.plot(x,y1,c='r')
结果如下:
3、2000组数据
代码如下:
同20、200组数据,将p1=p.head(2000)
结果如下:
三、jupyter借助skleran重做第1题
1、20组数据
代码如下:
# 导入所需的模块
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
p=pd.read_excel('weights_heights(身高-体重数据集).xls','weights_heights')
#读取数据行数
p1=p.head(20)
x=p1["Height"]
y=p1["Weight"]
# 数据处理
# sklearn 拟合输入输出一般都是二维数组,这里将一维转换为二维。
y = np.array(y).reshape(-1, 1)
x = np.array(x).reshape(-1, 1)
# 拟合
reg = LinearRegression()
reg.fit(x,y)
a = reg.coef_[0][0] # 系数
b = reg.intercept_[0] # 截距
print('拟合的方程为:Y = %.4fX + (%.4f)' % (a, b))
c=reg.score(x,y) # 相关系数
print(f'相关回归系数为%.4f'%c)
# 可视化
prediction = reg.predict(y) # 根据高度,按照拟合的曲线预测温度值
plt.xlabel('身高')
plt.ylabel('体重')
plt.scatter(x,y)
y1 = a*x + b
plt.plot(x,y1,c='r')
结果如下:
2、200组数据
代码如下:
同上,将p.head()里的值改为200
结果如下:
3、2000组数据
代码如下:
同上,p.head()改为2000
结果如下:
总结
Excel和jupyter这两种办法都可以完成线性回归的实验。excel比较简单直接,选中不同组的数据后,就能直接输出结果;jupyter如果用最小二乘法来做的话,要自己编程设计函数,但可以用第三方库就方便多了,直接调用函数实现。