oneVsAll.m 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. % ====================== YOUR CODE HERE ======================
  17. % Instructions: You should complete the following code to train num_labels
  18. % logistic regression classifiers with regularization
  19. % parameter lambda.
  20. %
  21. % Hint: theta(:) will return a column vector.
  22. %
  23. % Hint: You can use y == c to obtain a vector of 1's and 0's that tell you
  24. % whether the ground truth is true/false for this class.
  25. %
  26. % Note: For this assignment, we recommend using fmincg to optimize the cost
  27. % function. It is okay to use a for-loop (for c = 1:num_labels) to
  28. % loop over the different classes.
  29. %
  30. % fmincg works similarly to fminunc, but is more efficient when we
  31. % are dealing with large number of parameters.
  32. %
  33. % Example Code for fmincg:
  34. %
  35. % % Set Initial theta
  36. % initial_theta = zeros(n + 1, 1);
  37. %
  38. % % Set options for fminunc
  39. % options = optimset('GradObj', 'on', 'MaxIter', 50);
  40. %
  41. % % Run fmincg to obtain the optimal theta
  42. % % This function will return theta and the cost
  43. % [theta] = ...
  44. % fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), ...
  45. % initial_theta, options);
  46. %
  47. initial_theta = zeros(n + 1, 1);
  48. options = optimset('GradObj', 'on', 'MaxIter', 50);
  49. %fprintf ('unique y %f\n', unique(y))
  50. for i = 1:num_labels
  51. %mask = mod(i, 10); % map to => 1,2,3..8,9,0
  52. %mask = i;
  53. c = i % zeros(rows(y), 1) + mask;
  54. %size(c)
  55. %size(y ==c)
  56. [theta] = fmincg (@(t)(lrCostFunction(t, X, (y == c), lambda)), initial_theta, options);
  57. %size(theta)
  58. % copy the theta values for each classifier into the corresponding row of all_theta matrix
  59. all_theta(i,:) = theta';
  60. endfor
  61. % =========================================================================
  62. end