我使用Octave实现了一个梯度下降算法,以最小化成本函数,从而获得一个假设,用于判断图像质量的好坏。这个想法在某种程度上基于Andrew Ng的机器学习课程中的算法。
因此,我有880个“y”值,包含从0.5到约12的数值。我还有880个从50到300的“X”值,用于预测图像的质量。
遗憾的是,算法似乎失败了,经过几次迭代后,theta的值变得非常小,theta0和theta1变成了“NaN”。我的线性回归曲线也出现了奇怪的值…
这是梯度下降算法的代码:(theta = zeros(2, 1);
, alpha= 0.01, iterations=1500)
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)m = length(y); % number of training examplesJ_history = zeros(num_iters, 1);for iter = 1:num_iters tmp_j1=0;for i=1:m, tmp_j1 = tmp_j1+ ((theta (1,1) + theta (2,1)*X(i,2)) - y(i));end tmp_j2=0;for i=1:m, tmp_j2 = tmp_j2+ (((theta (1,1) + theta (2,1)*X(i,2)) - y(i)) *X(i,2)); end tmp1= theta(1,1) - (alpha * ((1/m) * tmp_j1)) tmp2= theta(2,1) - (alpha * ((1/m) * tmp_j2)) theta(1,1)=tmp1 theta(2,1)=tmp2 % ============================================================ % Save the cost J in every iteration J_history(iter) = computeCost(X, y, theta);endend
这是成本函数的计算方法:
function J = computeCost(X, y, theta) %m = length(y); % number of training examplesJ = 0;tmp=0;for i=1:m, tmp = tmp+ (theta (1,1) + theta (2,1)*X(i,2) - y(i))^2; %differenzberechnungendJ= (1/(2*m)) * tmpend
回答:
我认为你的computeCost
函数有问题。我去年参加了NG的课程,我有以下实现(向量化):
m = length(y);J = 0;predictions = X * theta;sqrErrors = (predictions-y).^2;J = 1/(2*m) * sum(sqrErrors);
其余的实现看起来不错,尽管你也可以将它们向量化。
theta_1 = theta(1) - alpha * (1/m) * sum((X*theta-y).*X(:,1));theta_2 = theta(2) - alpha * (1/m) * sum((X*theta-y).*X(:,2));
之后你正确地将临时theta(这里称为theta_1和theta_2)设置回“真实”的theta。
一般来说,向量化比使用循环更有用,阅读和调试时也更不容易出错。