predictOneVsAll.m 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. function p = predictOneVsAll(all_theta, X)
  2. %PREDICT Predict the label for a trained one-vs-all classifier. The labels
  3. %are in the range 1..K, where K = size(all_theta, 1).
  4. % p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions
  5. % for each example in the matrix X. Note that X contains the examples in
  6. % rows. all_theta is a matrix where the i-th row is a trained logistic
  7. % regression theta vector for the i-th class. You should set p to a vector
  8. % of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2
  9. % for 4 examples)
  10. m = size(X, 1);
  11. num_labels = size(all_theta, 1);
  12. % You need to return the following variables correctly
  13. p = zeros(size(X, 1), 1);
  14. v = zeros(size(X, 1), 1);
  15. % Add ones to the X data matrix
  16. X = [ones(m, 1) X];
  17. % ====================== YOUR CODE HERE ======================
  18. % Instructions: Complete the following code to make predictions using
  19. % your learned logistic regression parameters (one-vs-all).
  20. % You should set p to a vector of predictions (from 1 to
  21. % num_labels).
  22. %
  23. % Hint: This code can be done all vectorized using the max function.
  24. % In particular, the max function can also return the index of the
  25. % max element, for more information see 'help max'. If your examples
  26. % are in rows, then, you can use max(A, [], 2) to obtain the max
  27. % for each row.
  28. %
  29. % refer to week 3 reading: multiclass classification: 1 vs all
  30. % at the last line it mentions picking the class that maximize h function
  31. XT = X * all_theta';
  32. [v,p] = max(XT, [], 2);
  33. %size(p)
  34. r = [v,p];
  35. unique(p);
  36. % =========================================================================
  37. end