【问题标题】:Different results in numpy vs matlabnumpy vs matlab的不同结果
【发布时间】:2016-12-20 02:37:31
【问题描述】:

我正在尝试使用 numpy 实现以前在 python 中的 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

python 中的测试用例和结果

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]]

【问题讨论】:

  • @Kartik "MATLAB results may be wrong" 真的不是一个有用的建议,没有详细的原因。
  • 我的评论被误解了。我正在与您分享我的经验,并且我建议您可以使用其他软件来解决此问题,如果可以的话。 (我知道您可能无法访问其他软件。)当我尝试一个简单的直方图时,解释为什么 MATLAB 结果是错误的,这是我当时没有研究或弄清楚的东西。我将其归咎于 MATLAB 的封闭源代码性质,并推测他们的测试中出现了一些问题,并继续使用 Python,我觉得使用它更加“在家”。

标签: python matlab numpy


【解决方案1】:

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) dsm@notebook:~/coding$ python peter.py
[[ 0.045 ]
 [ 0.155 ]
 [ 0.2225]
 [ 0.2   ]]

与您的 Matlab 结果匹配。

【讨论】:

    猜你喜欢
    • 2017-11-24
    • 2012-02-01
    • 2022-01-07
    • 2012-01-30
    • 1970-01-01
    • 2019-09-25
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多