2015-11-10 67 views
2

我試圖找出對多元梯度下降算法的Python代碼梯度下降算法的理解梯度,並已發現了幾個幾種實現這樣的:在NumPy的

import numpy as np 

# m denotes the number of examples here, not the number of features 
def gradientDescent(x, y, theta, alpha, m, numIterations): 
    xTrans = x.transpose() 
    for i in range(0, numIterations): 
     hypothesis = np.dot(x, theta) 
     loss = hypothesis - y 
     cost = np.sum(loss ** 2)/(2 * m) 
     print("Iteration %d | Cost: %f" % (i, cost)) 
     # avg gradient per example 
     gradient = np.dot(xTrans, loss)/m 
     # update 
     theta = theta - alpha * gradient 
    return theta 

從梯度下降的定義,梯度下降的表達式爲: [\frac{1}{m}\sum_{i=1}^m(h_\theta(x^{(i)})-y^{(i)})x_j^{(i)}]

然而,在numpy的,它被計算爲:np.dot(xTrans, loss)/m 能有人請解釋我們是如何得到這個numpy的表達?

回答

3

該代碼實際上非常簡單,將花費更多時間來閱讀代碼是有益的。

  • hypothesis - y是平方損失梯度(作爲每個分量的向量形式)的第一部分,並且這被設置爲loss變量。假設的計算看起來像是線性迴歸。
  • xTransx的轉置,所以如果我們點這兩個產品,我們就可以得到他們組件產品的總和。
  • 然後我們除以m得到平均值。

除此之外,代碼有一些python風格的問題。我們通常在Python中使用under_score而不是camelCase,所以例如函數應該是gradient_descent。比java更清晰不是嗎? :)