selectThreshold.m 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. function [bestEpsilon bestF1] = selectThreshold(yval, pval)
  2. %SELECTTHRESHOLD Find the best threshold (epsilon) to use for selecting
  3. %outliers
  4. % [bestEpsilon bestF1] = SELECTTHRESHOLD(yval, pval) finds the best
  5. % threshold to use for selecting outliers based on the results from a
  6. % validation set (pval) and the ground truth (yval).
  7. %
  8. bestEpsilon = 0;
  9. bestF1 = 0;
  10. F1 = 0;
  11. stepsize = (max(pval) - min(pval)) / 1000;
  12. for epsilon = min(pval):stepsize:max(pval)
  13. % ====================== YOUR CODE HERE ======================
  14. % Instructions: Compute the F1 score of choosing epsilon as the
  15. % threshold and place the value in F1. The code at the
  16. % end of the loop will compare the F1 score for this
  17. % choice of epsilon and set it to be the best epsilon if
  18. % it is better than the current choice of epsilon.
  19. %
  20. % Note: You can use predictions = (pval < epsilon) to get a binary vector
  21. % of 0's and 1's of the outlier predictions
  22. tp = sum((pval < epsilon) & (yval == 1));
  23. tn = sum((pval >= epsilon) & (yval == 0));
  24. fp = sum((pval < epsilon) & (yval == 0));
  25. fn = sum((pval >= epsilon) & (yval == 1));
  26. prec = tp / (tp + fp);
  27. rec = tp / (tp + fn);
  28. F1 = 2 * prec * rec / (prec + rec);
  29. % =============================================================
  30. if F1 > bestF1
  31. bestF1 = F1;
  32. bestEpsilon = epsilon;
  33. end
  34. end
  35. end