首页 > 解决方案 > Andrew Ng 使用 python 的 ML 课程练习:梯度下降

问题描述

我一直在尝试在 python 中实现 Andrew Ng 练习的解决方案,但不知道为什么我不能使梯度下降正常工作。这是我用于梯度下降的代码:

def gradientDescent(x, y, theta, alpha, num_iter):
  m=np.size(x,axis=0)
  for i in range(num_iter):
      hyp=np.dot(x,theta)
      theta = theta - (alpha / m) * np.dot(x.T,(np.dot(X, theta) - y))
      return theta
theta=gradientDescent(X, y, [[0],[0]], 0.01, 1500)

这是根据此代码的 theta:array([[0.05839135],[0.6532885 ]])

所需的值为:array([[-3.6303],[[1.1664]])

模型看起来像这样: 情节

这是我一直在关注的使用八度音阶的代码:

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

m = length(y); % number of training examples
J_history = zeros(num_iters, 1);

for iter = 1:num_iters
    theta=theta-alpha*(1/m)*X'*(X*theta-y)
    J_history(iter) = computeCost(X, y, theta)
end

end

另外为了找到参数,我尝试使用正规方程方法,它给出了准确的结果,这意味着其余代码都可以。

标签: pythonmachine-learninglinear-regressiongradient-descent

解决方案


您的代码看起来不错,除了第 5 行的错字(大写X应该是小写x),该hyp变量从未使用过,并且您应该传递theta作为 shape(2,)而不是(2,1)(即 as [0,0])。

我在一些玩具数据上进行了尝试,似乎有效:

theta_true = np.array([-3.6303, 1.1664])

n = 50
X = np.ones((n,2))
X[:,1] = np.linspace(0,5, n)
ytrue = np.dot(X, theta_true)
y = ytrue + np.random.randn(n)

plt.scatter(X[:,1], y, s=100, c='b', alpha=0.4)
plt.plot(X[:,1], ytrue, 'k--')

玩具数据的散点图

并运行您的(清理后的)梯度下降代码:

def gradientDescent(x, y, theta, alpha, num_iter):
    m = np.size(x,axis=0)
    for i in range(num_iter):
        theta = theta - (alpha / m) * np.dot(x.T,(np.dot(x, theta) - y))
    return theta

theta = gradientDescent(X, y, [0,0], 0.01, 1500)
theta
# array([-3.81920963,  1.22926242])

这对我来说似乎足够接近。


推荐阅读