TSPerformanceMeasure.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. def overlapintervals(i1, i2):
  2. """
  3. Calculate intersection of two lists of intervals.
  4. :param i1: list of intervals
  5. :param i2: list of intervals
  6. :return: list of intervals with overlap of both intervals only
  7. """
  8. ollist = []
  9. for i in i1:
  10. for j in i2:
  11. if j[0] < i[0]+i[1] and j[0]+j[1] > i[0]:
  12. ollist += [[max(i[0], j[0]),
  13. min(i[0]+i[1], j[0]+j[1])-max(i[0], j[0])]]
  14. return ollist
  15. def calcPrecisionRecall(detection, groundtruth, setlength):
  16. """
  17. Calculated precision and recall for intervals in time series
  18. :param detection: array with detected intervals
  19. :param groundtruth: array with ground truth
  20. :param setlength: length of time series
  21. :return: precision, recall
  22. """
  23. import numpy as np
  24. if len(groundtruth) == 0 and len(detection) == 0:
  25. precision = 1
  26. recall = 1
  27. else:
  28. # Turn detection into array
  29. detArray = IntervalsToBinary(detection, setlength)
  30. gtArray = IntervalsToBinary(groundtruth, setlength)
  31. if np.sum(gtArray) == 0:
  32. gtArray = -1 * (gtArray - 1)
  33. detArray = -1*(detArray-1)
  34. unique, counts = np.unique(detArray+gtArray, return_counts=True)
  35. countvalues = dict(zip(unique, counts))
  36. tp = countvalues[2] if 2 in countvalues else 0
  37. tn = countvalues[0] if 0 in countvalues else 0
  38. unique, counts = np.unique(detArray-gtArray, return_counts=True)
  39. countvalues = dict(zip(unique, counts))
  40. fp = countvalues[1] if 1 in countvalues else 0
  41. unique, counts = np.unique(gtArray-detArray, return_counts=True)
  42. countvalues = dict(zip(unique, counts))
  43. fn = countvalues[1] if 1 in countvalues else 0
  44. precision = tp / (tp + fp) if tp + fp > 0 else 0
  45. recall = tp / (fn + tp) if tp + fn > 0 else 0
  46. #print(detection, groundtruth, precision, recall)
  47. return precision, recall