回归算法之岭回归

xiaoxiao2021-02-28  523

1. 岭回归

首先,说一下岭回归名字的由来, w^=(XTX+λI)1XTy ,其中,I 是单位矩阵(对角线全是1,像”山岭“), λ 是岭系数(顾名思义…改变其数值可以改变单位矩阵对角线的值)其次,岭回归是基于最小二乘法 w^=(XTX)1XTy , 最小二乘法中有时候 XTX 可能不是满秩矩阵,也就是此时行列式为零,无法求逆 ( A1=1|A|A 其中 A 是伴随矩阵)

2. 公式

最小二乘法 w^=(XTX)1XTy 岭回归公式 w^=(XTX+λI)1XTy

3. 伪代码

输入XY 以及lambda系数 计算demo = XTX+lambda*I 判断是否为零 计算 ws = demo.I * xTy

4.代码

# coding:utf-8 import pylab as pl from numpy import * from datetime import datetime def loadData(fileName): labelMat = [] dataMat = [] with open(fileName) as txtFile: for line in txtFile.readlines(): labelMat.append(map(float, line.split())[-1]) dataMat.append(map(float, line.split())[0:-1]) return dataMat, labelMat # 4177*8 # 计算ws #(xTx+IMat).I * xTy def ridge(xArr, yArr, lam=0.2): n = shape(xArr)[-1] IMat = eye(n) xTx = xArr.T * xArr demo = xTx + IMat * lam if linalg.det(demo) is 0: print "Warning !!!" return ws = demo.I * (xArr.T * yArr) # print ws return ws # 进行30次循环 每次的系数指数级改变 # 数据进行标准化 y-ymean,x=(x-xmean)/xvar def rightTest(xArr, yArr, loopNum=30): xMat = mat(xArr) yMat = mat(yArr).T yMat -= mean(yMat, 0) xMat = (xMat - mean(xMat, 0)) / var(xMat, 0) weight = zeros((loopNum, shape(xMat)[1])) for i in range(loopNum): weight[i, :] = ridge(xMat, yMat, exp(i - 10)).T return weight # 打印图像 def outPic(point): fig = pl.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(point) pl.show() if __name__ == '__main__': start = datetime.now() data, label = loadData("abalone.txt") loopNum = 30 w = rightTest(data, label, loopNum) # print w outPic(w) print "耗时为:", datetime.now() - start

5. 打印图像 以及 分析

(横轴是循环次数就是相关岭系数 纵轴是回归系数) 从图像中可以看出,在这八个系数中有两个距离0比较远,所以数据的主要预测就可以依靠这两个系数

附 数据集

''' 1 0.455 0.365 0.095 0.514 0.2245 0.101 0.15 15 1 0.35 0.265 0.09 0.2255 0.0995 0.0485 0.07 7 -1 0.53 0.42 0.135 0.677 0.2565 0.1415 0.21 9 1 0.44 0.365 0.125 0.516 0.2155 0.114 0.155 10 0 0.33 0.255 0.08 0.205 0.0895 0.0395 0.055 7 0 0.425 0.3 0.095 0.3515 0.141 0.0775 0.12 8 -1 0.53 0.415 0.15 0.7775 0.237 0.1415 0.33 20 -1 0.545 0.425 0.125 0.768 0.294 0.1495 0.26 16 1 0.475 0.37 0.125 0.5095 0.2165 0.1125 0.165 9 -1 0.55 0.44 0.15 0.8945 0.3145 0.151 0.32 19 -1 0.525 0.38 0.14 0.6065 0.194 0.1475 0.21 14 1 0.43 0.35 0.11 0.406 0.1675 0.081 0.135 10 1 0.49 0.38 0.135 0.5415 0.2175 0.095 0.19 11 -1 0.535 0.405 0.145 0.6845 0.2725 0.171 0.205 10 -1 0.47 0.355 0.1 0.4755 0.1675 0.0805 0.185 10 1 0.5 0.4 0.13 0.6645 0.258 0.133 0.24 12 0 0.355 0.28 0.085 0.2905 0.095 0.0395 0.115 7 -1 0.44 0.34 0.1 0.451 0.188 0.087 0.13 10 1 0.365 0.295 0.08 0.2555 0.097 0.043 0.1 7 .....还有4000行 '''

岭回归公式伪代码代码打印图像 以及 分析附 数据集

转载请注明原文地址: https://www.6miu.com/read-36577.html

最新回复(0)