2
0

test_validation.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import unittest
  2. import os
  3. import numpy as np
  4. from glob import glob
  5. import shutil
  6. from bci_core import utils as ana_utils
  7. from bci_core.online import model_loader
  8. from training import train_model, model_saver
  9. from dataloaders import neo
  10. from online_sim import simulation
  11. from validation import val_by_epochs
  12. class TestOnlineSim(unittest.TestCase):
  13. @classmethod
  14. def setUpClass(cls):
  15. root_path = './tests/data'
  16. raw, cls.event_id = neo.raw_loader(root_path, {'flex': ['1', '2']})
  17. cls.raw = raw
  18. # split into 2 pieces
  19. t_min, t_max = raw.times[0], raw.times[-1]
  20. t_mid = raw.times[len(raw.times) // 2]
  21. raw_train = raw.copy().crop(tmin=t_min, tmax=t_mid, include_tmax=True)
  22. cls.raw_val = raw.copy().crop(tmin=t_mid, tmax=t_max)
  23. # reconstruct single event for validation
  24. if cls.raw_val.annotations.onset[0] > t_mid:
  25. # correct time by first timestamp
  26. cls.raw_val.annotations.onset -= t_mid
  27. # train with the first half
  28. model = train_model(raw_train, event_id=cls.event_id, model_type='baseline')
  29. model_saver(model, './tests/data/', 'baseline', 'test', cls.event_id)
  30. cls.model_path = glob(os.path.join('./tests/data/', 'test', '*.pkl'))[0]
  31. @classmethod
  32. def tearDownClass(cls) -> None:
  33. shutil.rmtree(os.path.join('./tests/data/', 'test'))
  34. return super().tearDownClass()
  35. def test_event_metric(self):
  36. event_gt = np.array([[0, 0, 0], [5, 0, 1], [7, 0, 0], [9, 0, 2]])
  37. event_pred = np.array([[1, 0, 0], [4, 0, 1], [6, 0, 1], [7, 0, 0], [10, 0, 1], [11, 0, 2]])
  38. fs = 1
  39. precision, recall, f1_score = ana_utils.event_metric(event_gt, event_pred, fs, ignore_event=(0,))
  40. self.assertEqual(f1_score, 2 / 3)
  41. self.assertEqual(precision, 1 / 2)
  42. self.assertEqual(recall, 1)
  43. def test_sim(self):
  44. model = model_loader(self.model_path,
  45. state_change_threshold=0.7,
  46. state_trans_prob=0.7)
  47. metric_hmm, metric_nohmm, fig_pred = simulation(self.raw, self.event_id, model=model, epoch_length=1., step_length=0.1)
  48. fig_pred.savefig('./tests/data/pred.pdf')
  49. self.assertTrue(metric_hmm[-2] > 0.3) # f1-score (with hmm)
  50. self.assertTrue(metric_nohmm[-2] < 0.15) # f1-score (without hmm)
  51. def test_val_model(self):
  52. metrices, fig_conf = val_by_epochs(self.raw_val, self.model_path, self.event_id, 1.)
  53. fig_conf.savefig('./tests/data/conf.pdf')
  54. self.assertGreater(metrices[0], 0.85)
  55. self.assertGreater(metrices[1], 0.7)
  56. self.assertGreater(metrices[2], 0.7)
  57. if __name__ == '__main__':
  58. unittest.main()