Logistic回归(三)改进随机梯度上升
转载请注明作者和出处:https://blog.csdn.net/weixin_45814668
微信公众号:qiongjian0427
知乎:https://www.zhihu.com/people/qiongjian0427
Github:https://github.com/qiongjian/Machine-learning/
运行环境:anaconda—jupyter notebook
Python版本: Python3.x
回归系数与迭代次数的关系
判断优化算法的优劣的可靠方法是看它是否收敛,也就是看参数是否稳定。
由上图可知,x2只经过50次迭代就达到了稳定值,但其他两个需要更多次迭代。
对此进行改进的随机梯度上升算法的代码如下:
def stoGradAscent1(dataMatrix, classLabels, numIter = 150):
#m为行 n为列
m,n = shape(dataMatrix)
weights = ones(n)
# 随机梯度, 循环150,观察是否收敛
for j in range (numIter):
# [0, 1, 2 .. m-1]
dataIndex = range(m)
for i in range(m):
#alpha会随着迭代次数不断减小,但不会是0
alpha = 4 / (1.0 + j + i) + 0.01
randIndex = int(random.uniform(0, len(dataIndex)))
#随机选取更新
h = sigmoid(sum(dataMatrix[randIndex] * weights))
error = classLabels[randIndex] - h
weights = weights + alpha * error * dataMatrix[randIndex]
del (list(dataIndex)[randIndex])
return weights
有三点改进:
1.alpha每次迭代的时候都会调整。不会减小到0,满足某个条件时也不是严格下降的。
2.随机选取样本来更新回归系数,这种做法会减少周期性波动。
3.增加了迭代参数的设置。默认为150次,如果给定,将会按照新的参数值进行迭代。
运行结果:
dataArr,labelMat = loadDataSet()
weights=stoGradAscent1(array(dataArr),labelMat)
plotBestFit(weights)
效果很好,而且计算量少。
可以看一下改进后的回归系数和迭代次数的关系图。
1.这图的系数没有上图那样出现周期性的波动。
2.水平轴比上图短了很多。
END.