oneVsAll.m 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. function [all_theta] = oneVsAll(X, y, num_labels, lambda)
  2. %ONEVSALL trains multiple logistic regression classifiers and returns all
  3. %the classifiers in a matrix all_theta, where the i-th row of all_theta
  4. %corresponds to the classifier for label i
  5. % [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels
  6. % logistic regression classifiers and returns each of these classifiers
  7. % in a matrix all_theta, where the i-th row of all_theta corresponds
  8. % to the classifier for label i
  9. % Some useful variables
  10. m = size(X, 1);
  11. n = size(X, 2);
  12. % You need to return the following variables correctly
  13. all_theta = zeros(num_labels, n + 1);
  14. % Add ones to the X data matrix
  15. X = [ones(m, 1) X];
  16. for c = 1:num_labels
  17. initial_theta = zeros(n + 1, 1);
  18. options = optimset('GradObj', 'on', 'MaxIter', 50);
  19. all_theta(c,:) = (fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), initial_theta, options))';
  20. end
  21. % ====================== YOUR CODE HERE ======================
  22. % Instructions: You should complete the following code to train num_labels
  23. % logistic regression classifiers with regularization
  24. % parameter lambda.
  25. %
  26. % Hint: theta(:) will return a column vector.
  27. %
  28. % Hint: You can use y == c to obtain a vector of 1's and 0's that tell you
  29. % whether the ground truth is true/false for this class.
  30. %
  31. % Note: For this assignment, we recommend using fmincg to optimize the cost
  32. % function. It is okay to use a for-loop (for c = 1:num_labels) to
  33. % loop over the different classes.
  34. %
  35. % fmincg works similarly to fminunc, but is more efficient when we
  36. % are dealing with large number of parameters.
  37. %
  38. % Example Code for fmincg:
  39. %
  40. % % Set Initial theta
  41. % initial_theta = zeros(n + 1, 1);
  42. %
  43. % % Set options for fminunc
  44. % options = optimset('GradObj', 'on', 'MaxIter', 50);
  45. %
  46. % % Run fmincg to obtain the optimal theta
  47. % % This function will return theta and the cost
  48. % [theta] = ...
  49. % fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
  50. % initial_theta, options);
  51. %
  52. % =========================================================================
  53. end