首页 > 解决方案 > 在 learningcurve.m 中包含 lambda 时,在 linearRegCostFunction.m 中出现 lambda 未定义错误

问题描述

我得到 lambda undefined errr,即使我已经定义了 lambda=0 两次。仅当我在 learningcurve.m 函数中包含 lambda 变量时才会发生此错误。如果我注释掉 for 循环,它运行良好,但是我确实收到了一些警告。这是来自 andrew ng 机器学习课程第 6 周。我鼓励您检查 ex5.m 我已包含此主文件的链接

https://github.com/AladdinPerzon/Courses/blob/master/MOOCS/Coursera-Machine-Learning/Programming%20Assignment%205/ex5/ex5.m

function [error_train, error_val] =learningCurve(X, y, Xval, yval, lambda)

% Number of training examples
m = size(X, 1);

% You need to return these values correctly
error_train = zeros(m, 1);
error_val   = zeros(m, 1);

for i=1:m   
  [theta]=trainLinearReg([ones(i, 1), X(1:i, :)], y(1:i,:),lambda);
  [error_train(i), ~]=linearRegCostFunction(X(1:i,:),y(1:i),0);
  [error_val(i), ~]=linearRegCostFunction(Xval,yval,theta,0);
  
endfor
end
m = length(y); % number of training examples

% You need to return the following variables correctly 
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost and gradient of regularized linear 
%               regression for a particular choice of theta.
%
%               You should set J to the cost and grad to the gradient.
%

h = X * theta;

theta = [0 ; theta(2:end , :)];
pen_reg = lambda*(dot(theta,theta))/(2*m);
J = 1/(2 * m) * sum((h - y).^2) + pen_reg;

pen_grad = (lambda/m).*theta;
grad = 1/m .* ((h-y)' * X)' + pen_grad;

标签: machine-learningoctave

解决方案


推荐阅读