test_validation.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import unittest
  2. import os
  3. import numpy as np
  4. from glob import glob
  5. import shutil
  6. import mne
  7. from bci_core import utils as ana_utils
  8. from bci_core.online import model_loader
  9. from training import train_model, model_saver
  10. from dataloaders import neo
  11. from online_sim import simulation, _construct_model_event
  12. from validation import val_by_epochs
  13. class TestOnlineSim(unittest.TestCase):
  14. @classmethod
  15. def setUpClass(cls):
  16. root_path = './tests/data'
  17. raw_train, cls.event_id = neo.raw_loader(root_path, {'flex': ['1']})
  18. cls.raw_val, _ = neo.raw_loader(root_path, {'flex': ['2']}, upsampled_epoch_length=None)
  19. # train with the first half
  20. model = train_model(raw_train, event_id=cls.event_id, model_type='baseline')
  21. model_saver(model, './tests/data/', 'baseline', 'test', cls.event_id)
  22. cls.model_path = glob(os.path.join('./tests/data/', 'test', '*.pkl'))[0]
  23. @classmethod
  24. def tearDownClass(cls) -> None:
  25. shutil.rmtree(os.path.join('./tests/data/', 'test'))
  26. return super().tearDownClass()
  27. def test_event_metric(self):
  28. event_gt = np.array([[0, 0, 0], [5, 0, 1], [7, 0, 0], [9, 0, 2]])
  29. event_pred = np.array([[1, 0, 0], [4, 0, 1], [6, 0, 1], [7, 0, 0], [10, 0, 1], [11, 0, 2]])
  30. fs = 1
  31. precision, recall, f1_score = ana_utils.event_metric(event_gt, event_pred, fs, ignore_event=(0,))
  32. self.assertEqual(f1_score, 2 / 3)
  33. self.assertEqual(precision, 1 / 2)
  34. self.assertEqual(recall, 1)
  35. def test_construct_event(self):
  36. seq_1 = [(1, -1), (2, -1), (3, -1), (4, 1)]
  37. seq_2 = [(1, 0), (2, 0), (4, 1)]
  38. gt = [[1, 0, 0], [4, 0, 1]]
  39. ret_ = _construct_model_event(seq_1, 1, start_cond=0)
  40. self.assertTrue(np.allclose(gt, ret_))
  41. ret_ = _construct_model_event(seq_2, 1, start_cond=0)
  42. self.assertTrue(np.allclose(gt, ret_))
  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_val, 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.7) # f1-score (with hmm)
  50. self.assertTrue(metric_nohmm[-2] < 0.4) # 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()