机器学习——回归中的相关度与R平方值及其应用
程序员文章站
2024-03-08 09:10:28
...
1、皮尔逊相关系数(Pearson Correlation Coeffident)
(1)衡量两个值线性相关的强度
(2)取值范围[-1,1]:正向相关>0;负向相关<0;无相关性=0.
(3)公式:,其中,Cov(X,Y)是相关性方差;Var(X):X的方差;Var(Y):Y的方差
2、计算方法举例
结合上面的公式并利用excel计算出皮尔逊相关系数r:
3、其他举例
4、R平方值
(1)定义:决定系数,反映因变量的全部变异能通过回归关系被自变量解释的比例。
(2)描述:如R平方为0.8,则表示回归关系可以解释因变量80%的变异。换句话说,如果我们能控制自变量不变,则因变量的变异程度会减少80%.
(3)简单线性回归:R^2 = r*r
多元线性回归:
三者之间的关系:SST = SSR+SSE
5、R平方的局限性:
R平方会随着自变量的增加会变大,R平方和样本量是有关系的。因此,要对得到的R平方进行修正,修正方法如下:
6、在Python中实现相关度与R平方值
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import numpy as np
import math
from astropy.units import Ybarn
#相关度
def computeCorrelation(X,Y):
xBar = np.mean(X)
yBar = np.mean(Y)
SSR = 0
varX = 0
varY = 0
for i in range(0,len(X)):
diffXXBar = X[i] - xBar
diffYYBar = Y[i] - yBar
SSR += (diffXXBar * diffYYBar)
varX += diffXXBar ** 2
varY += diffYYBar ** 2
SST = math.sqrt(varX * varY)
return SSR / SST
#多项式回归
def polyfit(x,y,degree): #degree是x的次数,此处为:1
results = {}
coeffs = np.polyfit(x,y,degree) #对传入的参数自动计算回归方程
results['polynomial'] = coeffs.tolist() #转换成列表
p = np.poly1d(coeffs)
yhat = p(x)
ybar = np.sum(y)/len(y)
ssreg = np.sum((yhat-ybar)**2)
print("ssreg:",str(ssreg))
sstot = np.sum((y-ybar)**2)
print("sstot:",str(sstot))
results['determination'] = ssreg/sstot
print("results:",results)
return results
testX = [1,3,8,7,9]
testY = [10,12,24,21,34]
print("r:",computeCorrelation(testX,testY))
print("r^2:",str(computeCorrelation(testX,testY)**2)) #简单线性回归的决定系数
print(polyfit(testX,testY,1)['determination'])
运行结果:
r: 0.940310076545
r^2: 0.884183040052
ssreg: 333.160169492
sstot: 376.8
results: {'polynomial': [2.65677966101695, 5.322033898305076], 'determination': 0.88418304005181958}
0.884183040052