我正在尝试实现一个渐变下降算法,这个算法之前用python编写的matlab中有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
Run Code Online (Sandbox Code Playgroud)
和我的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 …
Run Code Online (Sandbox Code Playgroud)