我试图实现一个梯度下降算法,这个算法以前是用matlab用python和numpy编写的,但是我得到了一组相似但不同的结果。在
这是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版本
^{pr2}$
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]]