You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

oneVsAll.m 2.4 kB

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

机器学习

Contributors (1)