我使用梯度下降算法实现了一个代价函数,以获得一种假设来判断图像的质量。我是用Octave完成的。这个想法在某种程度上基于Andrew Ng的机器学习课程中的算法。
因此,我有880个值为0.5到~12的"y"值。我有880个值为50到300的"X"值,应该预测图像的质量。
不幸的是,算法似乎失败了,经过一些迭代后,theta的值变得非常小,theta0和theta1变成了"NaN"。我的线性回归曲线有奇怪的值...
以下是梯度下降算法的代码: (
因此,我有880个值为0.5到~12的"y"值。我有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 examples
J_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);
end
end
这里是成本函数的计算:
function J = computeCost(X, y, theta) %
m = length(y); % number of training examples
J = 0;
tmp=0;
for i=1:m,
tmp = tmp+ (theta (1,1) + theta (2,1)*X(i,2) - y(i))^2; %differenzberechnung
end
J= (1/(2*m)) * tmp
end