Linear Regression


SUBMITTED BY: Guest

DATE: Nov. 28, 2013, 10:55 p.m.

FORMAT: Text only

SIZE: 1.2 kB

HITS: 1267

  1. function [J, grad] = linearRegCostFunction(X, y, theta, lambda)
  2. %LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear
  3. %regression with multiple variables
  4. % [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the
  5. % cost of using theta as the parameter for linear regression to fit the
  6. % data points in X and y. Returns the cost in J and the gradient in grad
  7. % Initialize some useful values
  8. m = length(y); % number of training examples
  9. % You need to return the following variables correctly
  10. J = 0;
  11. grad = zeros(size(theta));
  12. % ====================== YOUR CODE HERE ======================
  13. % Instructions: Compute the cost and gradient of regularized linear
  14. % regression for a particular choice of theta.
  15. %
  16. % You should set J to the cost and grad to the gradient.
  17. %
  18. h = X*theta;
  19. J = sum (((h-y).^2))/(2*m)+ lambda * (sum(theta.^2)-theta(1,1)^2)/(2*m);
  20. grad = X'*(h-y)/m;
  21. thetaT = theta;
  22. thetaT(1,1)=0;
  23. grad =grad + (lambda*thetaT)/m ;
  24. % =========================================================================
  25. grad = grad(:);
  26. end

comments powered by Disqus