1. 程式人生 > >機器學習實戰第五章Logistic回歸

機器學習實戰第五章Logistic回歸

表示 article err () tail mat cycle col transpose


def
gradAscent(dataMatIn, classLabels): dataMatrix = mat(dataMatIn) #convert to NumPy matrix labelMat = mat(classLabels).transpose() #convert to NumPy matrix m,n = shape(dataMatrix) alpha = 0.001 maxCycles = 500 weights = ones((n,1)) for k in range(maxCycles): #
heavy on matrix operations h = sigmoid(dataMatrix*weights) #matrix mult error = (labelMat - h) #vector subtraction weights = weights + alpha * dataMatrix.transpose()* error #matrix mult return weights

這是書中梯度上升算法的代碼,但看到倒數第三行和倒數第二行的時候就懵逼了,書中說這裏略去了一個簡單的數據推導,嚶嚶嚶,想了一會沒想出來,於是乎就百度看看大神的解釋,這是找到的一篇解釋的比較好的,仔細一看發現是在Ag的機器學習視頻中講過的,忘了。。。

Sigmoid函數: $g(z)=\frac{1}{1+e^{-z}}$

  $h_{\theta }(x)=g(\theta ^{T}x)$

這裏$\theta$和書中w一樣,表示系數

代價函數如下,代價函數是用來計算預測值(類別)與實際值(類別)之間的誤差的

  $cost(h_{\theta} (x),y)=\left\{\begin{matrix}
  -log(h_{\theta}(x)), y=1\\
  -log(1-h_{\theta}(x)), y=0\end{matrix}\right.$

寫在一起表示為:

  $cost(h_{\theta} (x),y)=-ylog(h_{\theta}(x))-(1-y)log(1-h_{\theta}(x))$

總體的代價函數為:

  $J(\theta)=\frac{1}{m}\sum_{m}^{i=1}cost(h_{\theta} (x^{(i)}),y^{(i)})=\frac{1}{m}\sum_{m}^{i=1}-y^{(i)}log(h_{\theta}(x^{(i)}))-(1-y^{(i)})log(1-h_{\theta}(x^{(i)}))$

要使誤差最小,即求$J(\theta)$最小,也可以轉化成就$-J(\theta)$的最大值,可以用梯度上升算法來求最大值,

    $\theta := \theta+ \alpha \frac{\partial J(\theta )}{\partial \theta_{j}}$

下面是推導過程:

  技術分享圖片

所以權重的叠代更新公式為:

  $\theta_{j} = \theta_{j}+ \alpha \sum_{m}^{i=1}(y_{i}-h_{\theta}(x^{(i)}))x^{(i))}$

機器學習實戰第五章Logistic回歸