utils.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #! /usr/bin/python
  2. # -*- encoding: utf-8 -*-
  3. import numpy
  4. import torch
  5. import torch.nn.functional as F
  6. from sklearn import metrics
  7. from operator import itemgetter
  8. def accuracy(output, target, topk=(1,)):
  9. """Computes the precision@k for the specified values of k"""
  10. maxk = max(topk)
  11. batch_size = target.size(0)
  12. _, pred = output.topk(maxk, 1, True, True)
  13. pred = pred.t()
  14. correct = pred.eq(target.view(1, -1).expand_as(pred))
  15. res = []
  16. for k in topk:
  17. correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
  18. res.append(correct_k.mul_(100.0 / batch_size))
  19. return res
  20. def tuneThresholdfromScore(scores, labels, target_fa, target_fr = None):
  21. fpr, tpr, thresholds = metrics.roc_curve(labels, scores, pos_label=1)
  22. fnr = 1 - tpr
  23. tunedThreshold = [];
  24. if target_fr:
  25. for tfr in target_fr:
  26. idx = numpy.nanargmin(numpy.absolute((tfr - fnr)))
  27. tunedThreshold.append([thresholds[idx], fpr[idx], fnr[idx]]);
  28. for tfa in target_fa:
  29. idx = numpy.nanargmin(numpy.absolute((tfa - fpr))) # numpy.where(fpr<=tfa)[0][-1]
  30. tunedThreshold.append([thresholds[idx], fpr[idx], fnr[idx]]);
  31. idxE = numpy.nanargmin(numpy.absolute((fnr - fpr)))
  32. eer = max(fpr[idxE],fnr[idxE])*100
  33. return (tunedThreshold, eer, fpr, fnr);