(一)用excel中数据分析功能做线性回归练习。分别选取20、200、2000(或20000)组数据,进行练习。记录回归方程式、相关系数R2
(二)用jupyter编程(不借助第三方库),用最小二乘法;
新建项目输入代码:
import pandas as pd
def read_file(raw):#根据行数来读取文件
df = pd.read_excel('D:/GoogleDownload/weights_heights(身高-体重数据集).xls',sheet_name ='weights_heights')
height=df.iloc[0:raw,1:2].values
weight=df.iloc[0:raw,2:3].values
return height,weight
def array_to_list(array):#将数组转化为列表
array=array.tolist()
for i in range(0,len(array)):
array[i]=array[i][0]
return array
def unary_linear_regression(x,y):#一元线性回归,x,y都是列表类型
xi_multiply_yi=0
xi_square=0;
x_average=0;
y_average=0;
f=x
for i in range(0,len(x)):
xi_multiply_yi+=x[i]*y[i]
x_average+=x[i]
y_average+=y[i]
xi_square+=x[i]*x[i]
x_average=x_average/len(x)
y_average=y_average/len(x)
b=(xi_multiply_yi-len(x)*x_average*y_average)/(xi_square-len(x)*x_average*x_average)
a=y_average-b*x_average
for i in range(0,len(x)):
f[i]=b*x[i]+a
R_square=get_coefficient_of_determination(f,y,y_average)
print('R_square='+str(R_square)+'\n'+'a='+str(a)+' b='+str(b))
def get_coefficient_of_determination(f,y,y_average):#传输计算出的值f和x,y的真实值还有平均值y_average,获取决定系数,也就是R²
res=0
tot=0
for i in range(0,len(y)):
res+=(y[i]-f[i])*(y[i]-f[i])
tot+=(y[i]-y_average)*(y[i]-y_average)
R_square=1-res/tot
return R_square
raw=[20,200,2000,20000]
for i in raw:
print('数据组数为'+str(i)+":")
height,weight=read_file(i)
height=array_to_list(height)
weight=array_to_list(weight)
unary_linear_regression(height,weight)
结果如下:
(三)用jupyter编程,借助skleran
创建项目输入代码:
from sklearn import linear_model
from sklearn.metrics import r2_score
import numpy as np
import pandas as pd
def read_file(raw):#根据行数来读取文件
df = pd.read_excel('D:/GoogleDownload/weights_heights(身高-体重数据集).xls',sheet_name ='weights_heights')
height=df.iloc[0:raw,1:2].values
weight=df.iloc[0:raw,2:3].values
return height,weight
raw=[20,200,2000,20000]#要读取的行数
for i in raw:
print('数据组数为'+str(i)+":")
height,weight=read_file(i)
weight_predict=weight
lm = linear_model.LinearRegression()
lm.fit(height,weight)
b=lm.coef_
a=lm.intercept_
weight_predict=lm.predict(height)#计算有方程推测出来的值
R_square=r2_score(weight,weight_predict)#计算方差
print('b='+str(b[0][0])+' a='+str(a[0]))
print('R_square='+str(R_square))
结果如下: