2016-08-13 105 views
0

我想实现一个先前用matlab中的numpy编写的梯度下降算法,但是我得到了一组类似但不同的结果。在numpy与matlab中的不同结果

这里的MATLAB代码

function [theta] = gradientDescentMulti(X, y, theta, alpha, num_iters) 

m = length(y); 
num_features = size(X,2); 
for iter = 1:num_iters; 
    temp_theta = theta; 
    for i = 1:num_features 
     temp_theta(i) = theta(i)-((alpha/m)*(X * theta - y)'*X(:,i)); 
    end 
    theta = temp_theta; 
end 


end 

和我的Python版本

def gradient_descent(X,y, alpha, trials): 

    m = X.shape[0] 
    n = X.shape[1] 
    theta = np.zeros((n, 1)) 

    for i in range(trials): 

     temp_theta = theta 
     for p in range(n): 
      thetaX = np.dot(X, theta) 
      tMinY = thetaX-y 
      temp_theta[p] = temp_theta[p]-(alpha/m)*np.dot(tMinY.T, X[:,p:p+1]) 

     theta = temp_theta 

    return theta 

测试用例和MATLAB结果

X = [1 2 1 3; 1 7 1 9; 1 1 8 1; 1 3 7 4] 
y = [2 ; 5 ; 5 ; 6]; 
[theta] = gradientDescentMulti(X, y, zeros(4,1), 0.01, 1); 

theta = 

    0.0450 
    0.1550 
    0.2225 
    0.2000 

测试用例,并导致蟒蛇

test_X = np.array([[1,2,1,3],[1,7,1,9],[1,1,8,1],[1,3,7,4]]) 
test_y = np.array([[2], [5], [5], [6]]) 
theta, cost = gradient_descent(test_X, test_y, 0.01, 1) 
print theta 
>>[[ 0.045  ] 
    [ 0.1535375 ] 
    [ 0.20600144] 
    [ 0.14189214]] 
+0

@Kartik“MATLAB结果可能是错误的”真的不是一个有用的建议,没有详细的理由。 – dbliss

+0

我的评论被误解了。我与您分享我的经验,并且我建议您可以使用其他软件来解决此问题。 (我知道你可能无法访问另一个软件。)当我尝试一个简单的直方图时,解释为什么MATLAB结果是错误的,这是我当时没有研究或弄清楚的事情。我把它归咎于MATLAB的封闭源代码本质,并假定某些东西在测试中滑落,并继续使用Python,这让我感觉更“在家”使用。 – Kartik

回答

7

这条线在你的Python:

temp_theta = theta 

没有做什么,你认为它。它不复制theta并将其“分配”给“变量”temp_theta - 它只是说“temp_theta现在是当前由theta命名的对象的新名称”。

所以当你修改temp_theta这里:

 temp_theta[p] = temp_theta[p]-(alpha/m)*np.dot(tMinY.T, X[:,p:p+1]) 

你实际上修改theta - 因为那里有两个名字只有一个阵列,现在。

如果改为写

temp_theta = theta.copy() 

你就会得到这样

(3.5) [email protected]:~/coding$ python peter.py 
[[ 0.045 ] 
[ 0.155 ] 
[ 0.2225] 
[ 0.2 ]] 

符合你Matlab的结果。

相关问题