其中 a是?定义参数, I则是单位矩阵
w=(x.T * x +aI).I * X.T * y
In [3]:
#对于对单位矩阵的?成,需要借助NumPy中的eye函数,该函数需要输?对?矩阵规模参数 import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt np.eye(3)
def ridgeRegres(dataSet, lam=0.2): xMat = np.mat(dataSet.iloc[:, :-1].values) yMat = np.mat(dataSet.iloc[:, -1].values).T xTx = xMat.T * xMat denom = xTx + np.eye(xMat.shape[1])*lam ws = denom.I * (xMat.T * yMat) return ws
aba = pd.read_table(‘abalone.txt‘, header = None)#该数据集源于UCI,记录了鲍?的?物属性,?标字段是该?物的年龄 aba.head()
#其中最后?列为标签列,同时,由于数据集第?列是分类变量,且没有?于承载截距系数的列,因此 #此处将第?列的值全部修改为1,然后再进?建模 aba.iloc[:, 0] = 1 aba.head()
rws = ridgeRegres(aba) rws #返回各列的系数同样的第一行为截距
#封装R**2 def rSquare(dataSet, regres):#设置参数为 数据集 与 回归方法 sse = sseCal(dataSet, regres) y = dataSet.iloc[:, -1].values sst = np.power(y - y.mean(), 2).sum() return 1 - sse / sst
In [10]:
#封装最小二乘 def standRegres(dataSet): xMat = np.mat(dataSet.iloc[:, :-1].values)#将DataFrame转换成array 再将array转换成matrix(矩阵) 因为只有矩阵可以进行计算 yMat = np.mat(dataSet.iloc[:, -1].values).T xTx = xMat.T*xMat if np.linalg.det(xTx) == 0:#判断xTx是否是满秩矩阵,若不满秩,则?法对其进?求逆矩阵的操作 print("This matrix is singular, cannot do inverse") return ws = xTx.I * (xMat.T*yMat) return ws #这?需要注意的是,当使?矩阵分解来求解多元线性回归时,必须添加?列全为1的列,?于表征线性?程截距b。
#将SSE做一个封装 def sseCal(dataSet, regres):#设置参数为 数据集 与 回归方法 n = dataSet.shape[0] y = dataSet.iloc[:, -1].values ws = regres(dataSet) yhat = dataSet.iloc[:, :-1].values * ws yhat = yhat.reshape([n,]) rss = np.power(yhat - y, 2).sum() return rss
rSquare(aba, ridgeRegres)
rSquare(aba, standRegres)
from sklearn import linear_model ridge = linear_model.Ridge(alpha=.2) ridge.fit(aba.iloc[:, :-1], aba.iloc[:, -1])
ridge.coef_#返回各行系数
ridge.intercept_#返回截距
def ridgeTest(dataSet): xMat = np.mat(dataSet.iloc[:, :-1].values) yMat = np.mat(dataSet.iloc[:, -1].values).T yMean = np.mean(yMat, axis = 0) yMat = yMat - yMean xMeans = np.mean(xMat, axis = 0) xVar = np.var(xMat,axis = 0) xMat = (xMat - xMeans)/xVar numTestPts = 30 wMat = np.zeros((numTestPts,xMat.shape[1])) for i in range(numTestPts): ws = ridgeRegres(dataSet,np.exp(i-10)) wMat[i,:]=ws.T return wMat
aba = pd.read_table(‘abalone.txt‘, header = None) ridgeWeights = ridgeTest(aba) plt.plot(ridgeWeights) plt.xlabel(‘log(lambda)‘) plt.ylabel(‘weights‘)
from sklearn import linear_model las = linear_model.Lasso(alpha = 0.01) las.fit(aba.iloc[:, :-1], aba.iloc[:, -1])
Out[22]:
ridge.coef_#返回各行系数
ridge.intercept_#返回截距
原文:https://www.cnblogs.com/Koi504330/p/11909411.html