test_validation.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import unittest
  2. import os
  3. import numpy as np
  4. from bci_core import utils as ana_utils
  5. from training import train_model
  6. from dataloaders import library_ieeg
  7. from validation import validation
  8. class TestValidation(unittest.TestCase):
  9. @classmethod
  10. def setUpClass(cls):
  11. root_path = './tests/data'
  12. cls.event_id = {'ball': 2, 'rest': 0}
  13. raw = library_ieeg.raw_preprocessing(os.path.join(root_path, 'ecog-data/1', 'bp_mot_t_h.mat'), finger_model='ball')
  14. raw = raw.pick_channels([raw.info['ch_names'][i] for i in [5,6,7,12,13,14,20,21]])
  15. cls.raw = raw
  16. # split into 2 pieces
  17. t_min, t_max = raw.times[0], raw.times[-1]
  18. t_mid = raw.times[len(raw.times) // 2]
  19. raw_train = raw.copy().crop(tmin=t_min, tmax=t_mid, include_tmax=True)
  20. cls.raw_val = raw.copy().crop(tmin=t_mid, tmax=t_max)
  21. # reconstruct single event for validation
  22. if cls.raw_val.annotations.onset[0] > t_mid:
  23. # correct time by first timestamp
  24. cls.raw_val.annotations.onset -= t_mid
  25. # train with the first half
  26. cls.model = train_model(raw_train, event_id=cls.event_id, model_type='baseline')
  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_validation(self):
  36. (precision, recall, f1_score, r), fig_erds, fig_pred = validation(self.raw, 'baseline', self.event_id, model=self.model, state_change_threshold=0.7)
  37. fig_erds.savefig('./tests/data/erds.pdf')
  38. fig_pred.savefig('./tests/data/pred.pdf')
  39. self.assertTrue(f1_score > 0.9)
  40. self.assertTrue(r > 0.5)
  41. if __name__ == '__main__':
  42. unittest.main()