练习了一下吴恩达的《Programming Exercise 2: Logistic Regression》, 两点心得:
- 听课和做习题是两回事,代码是需要严格按照理论公式实现
- 体会到矩阵运算的强大威力,重复的计算不仅仅是可以通过for循环实现,更可以通过矩阵高效的计算
惨不忍睹的第一版,很算法,很C程序员:
- costFunction.m
for i = 1 : m,
J += -y(i)*log(sigmoid(X(i,:)*theta)) - (1 - y(i))*log(1 - sigmoid(X(i,:)*theta));
end;
for j = 2 : size(theta)(1),
for i = 1 : m,
grad(j) += (sigmoid(X(i,:)*theta) - y(i))*(X(i,:)(j));
end;
end;
J = J*(1/m);
grad = grad*(1/m);
- sigmoid.m
for i = 1 : size(z)(2),
g(i) = 1/(1 + exp(-1 * z(i)));
end;
改进后的实现,注意对参数进行适当的转置,以满足矩阵运算的行列要求。
- costFunction.m
J = 1/m * (-y'*log(sigmoid(X*theta)) - (1-y')*log(1 - sigmoid(X*theta)));
grad = 1/m * X'*(sigmoid(X*theta) - y);
sigmoid.m
g = 1./(1 + exp(-1 * z));
- costFunctionReg.m
J = 1/m * (-y'*log(sigmoid(X*theta)) - (1-y')*log(1 - sigmoid(X*theta))) + lambda/(2*m) * sum(theta(2:end).^2);
grad(1,:) = 1/m * (X(:, 1)' * (sigmoid(X*theta) - y));
grad(2:size(theta), :) = 1/m * X(:, 2:size(theta))' * (sigmoid(X*theta) - y) + lambda/m * theta(2:size(theta), :);
网友评论