上一節我們討論的隨機梯度上升算法在進行迭代的過程中迴歸係數會出現激烈的改變,這一節我們對上一節的算法進行改進:
def stocGradAscent1(dataMatrix, classLabels, numIter=150):
m,n = shape(dataMatrix)
weights = ones(n) #initialize to all ones
for j in range(numIter):
dataIndex = range(m)
for i in range(m):
alpha = 4/(1.0+j+i)+0.0001
randIndex = int(random.uniform(0,len(dataIndex)))
h = sigmoid(sum(dataMatrix[randIndex]*weights))
error = classLabels[randIndex] - h
weights = weights + alpha * error * dataMatrix[randIndex]
del(dataIndex[randIndex])
return weights
在這個改進的算法中我們增加了兩處代碼,步長會隨着迭代的次數增加而不斷減小,但是不會減小到0,如果處理的是動態變化的問題可以適當的加大常數項。第二處改進的地方是迴歸係數的更新是通過隨機選取樣本點來進行的。這樣可以減少週期性的波動。