python - 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
另外为了找到参数,我尝试使用正规方程方法,它给出了准确的结果,这意味着其余代码都可以。
解决方案
您的代码看起来不错,除了第 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])
这对我来说似乎足够接近。
推荐阅读
- java - 将谷歌表格数据同步检索到 android 应用程序
- amazon-web-services - 如何从 EC2 实例收集日志并将其存储在 S3 存储桶中?
- python - 有没有一种有效的方法来获取 pyshark 中的字段偏移量
- bash - 从过滤器位于第一列的第二列中选择匹配项
- javascript - 在 Date 上添加日期时的奇怪行为
- python - cx_Freeze + curses: 'NoneType' 对象没有属性 'fileno'
- css - 使用 SASS 导入自定义字体时出错
- r - R:匹配两个数据帧中的值,例如 vlookup,但对于没有 Key [大数据] 的多个条件
- ios - 如何过滤时间戳数组以保持特定时间?
- angular - 没有箭头功能的 Typescript/Angular2 委托