@richey
2016-04-15T12:16:25.000000Z
字数 6556
阅读 1478
机器学习
回归
梯度下降
先看个例子,比如,想用面积和卧室个数来预测房屋的价格
训练集如下:
首先,我们假设为线性模型,那么hypotheses定义为
为了求解这个最优化问题,即找到使得最小,可以有很多方法。
先介绍梯度下降法 ,这是一种迭代方法,先随意选取初始,比如,然后不断的以梯度的方向修正,最终使收敛到最小。
当然梯度下降找到的最优是局部最优,也就是说选取不同的初值,可能会找到不同的局部最优点,但是对于最小二乘的代价函数模型,比较简单只有一个最优点,所以局部最优即全局最优。
对于某个参数的梯度,其实就是对该参数求导的结果,所以对于某个参数每次调整的公式如下:
richey注解: 取, 是特征的纬度,注意到上式是对求偏导,因此第3个式子中只有,其他项对的偏导数为零。
就是求导过程,但是实际训练集中会有m个样本点,所以最终递推公式为:
重复迭代以下直至收敛{
所以提出一种stochastic gradient descent(随机梯度下降),想法很简单,即每次只考虑一个样本点,而不是所有样本点,那么公式就变为:
Loop{
for i in m,{
其推导过程的思路:
推导得出的矩阵表达式,梯度为零时的取得最小值。
首先考虑下图中的几种曲线拟合情况:
最左边的图使用线性拟合,但是可以看到数据点并不完全在一条直线上,因而拟合的效果并不好。如果我们加入项,得到,如中间图所示,该二次曲线可以更好的拟合数据点。
我们继续加入更高次项,可以得到最右边图所示的拟合曲线,可以完美地拟合数据点,最右边的图中曲线为5阶多项式,可是我们都很清醒地知道这个曲线过于完美了,对于新来的数据可能预测效果并不会那么好。
对于最左边的曲线,我们称之为欠拟合--过小的特征集合使得模型过于简单不能很好地表达数据的结构,最右边的曲线我们称之为过拟合--过大的特征集合使得模型过于复杂。
正如上述例子表明,在学习过程中,特征的选择对于最终学习到的模型的性能有很大影响,于是选择用哪个特征,每个特征的重要性如何就产生了加权的线性回归。在传统的线性回归中,学习过程如下:
richey注解:以上求和将m个样本同等看待
而加权线性回归学习过程如下:
1. Fit to minimaize
2. Output:
二者的区别就在于对不同的样本赋予了不同的非负值权重,权重越大,对于代价函数的影响越大。一般选取的权重计算公式为:
from numpy import *
import matplotlib.pyplot as plt
def loadDataSet(filename):
numFeat = len(open(filename).readline().split('\t'))-1
dataMat = []
labelMat = []
fr = open(filename)
for line in fr.readlines():
lineArr = []
curLine = line.strip('\n').split('\t')
for i in range(numFeat):
lineArr.append(float(curLine[i]))
dataMat.append(lineArr)
labelMat.append(float(curLine[-1]))
return dataMat, labelMat
def standMaReg(xArr, yArr):
xMat = mat(xArr)
yMat = mat(yArr).T
xTx = xMat.T*xMat
if linalg.det(xTx)==0.0:
print 'This matrix is singular, connot do inverse'
return
ws = xTx.I*(xMat.T*yMat)
return ws
def standBaGradReg(xArr, yArr, alpha=0.001, iter_num=15):
xMat = mat(xArr)
yMat = mat(yArr).T
m,n=shape(xMat)
weights = mat(ones((n,1)))
for i in range(iter_num):
yPredict = mat(xMat*weights)
tmp=mat(zeros((n,1)))
for j in range(n):
tmp[j,:] += alpha*sum(multiply((yMat-yPredict),xMat[:,j]))
weights = weights + tmp
return weights
def lwlr(testPoint, xArr, yArr, k=1.0):
xMat = mat(xArr)
yMat = mat(yArr).T
m = shape(xMat)[0]
weights = mat(eye((m)))
for j in range(m):
diffMat = testPoint - xMat[j,:]
weights[j,j] = exp(diffMat*diffMat.T/(-2.0*k**2))
xTx = xMat.T*(weights*xMat)
if linalg.det(xTx) == 0.0:
print "This matrix is singular, cannot do inverse"
return
ws = xTx.I*(xMat.T*(weights*yMat))
return testPoint*ws
def lwlrTest(testArr, xArr, yArr, k=1.0):
m = shape(testArr)[0]
yPre = zeros(m)
for i in range(m):
yPre[i] = lwlr(testArr[i], xArr, yArr, k)
return yPre
def ridgeRegres(xMat, yMat, lam=0.2):
xTx = xMat.T*xMat
denom = xTx + eye(shape(xMat)[1])*lam
if linalg.det(denom) == 0.0:
print "This matrix is singular, cannot do inverse"
ws = denom.I*(xMat.T*yMat)
return ws
def ridgeTest(xArr, yArr, numIter=30):
xMat = mat(xArr)
yMat = mat(yArr).T
yMean = mean(yMat,0)
yMat = yMat - yMean
xMeans = mean(xMat, 0)
xVar = var(xMat, 0)
xMat = (xMat - xMeans)/xVar
wMat = zeros((numIter,shape(xMat)[1]))
lamList = []
for i in range(numIter):
lamList.append(exp(i-10))
ws = ridgeRegres(xMat, yMat, exp(i-10))
wMat[i,:]=ws.T
return wMat, lamList
def plotReg(weights, xArr, yArr, xIndex=0):
xMat = mat(xArr)
yMat = mat(yArr)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xMat[:,xIndex].flatten().A[0], yMat.T[:,0].flatten().A[0])
yPredict = xMat*weights
ax.plot(xMat[:,xIndex], yPredict)
plt.show()
xArr, yArr = loadDataSet("ex0.txt")
ws1 = standMaReg(xArr, yArr)
print "ws1", ws1
plotReg(ws1, xArr, yArr, 1)
ws2 = standBaGradReg(xArr, yArr, 0.001, 1000)
print "ws2", ws2
yPre = lwlrTest(xArr, xArr, yArr, 0.01)
xMat = mat(xArr)
srtInde = xMat[:,1].argsort(0)
xSort = xMat[srtInde][:,0,:]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(xSort[:,1], yPre[srtInde])
ax.scatter(xMat[:,1].flatten().A[0], mat(yArr).T.flatten().A[0], s=2, c='red')
plt.show()
abX, abY = loadDataSet('abalone.txt')
weights, lam = ridgeTest(abX, abY)
plt.plot(weights)
plt.show()
1 http://www.cnblogs.com/fxjwind/p/3626173.html?utm_source=tuicool&utm_medium=referral
2 http://blog.csdn.net/moodytong/article/details/10041547
3 http://www.cnblogs.com/fanyabo/p/4060498.html