test_training.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import os
  2. import training
  3. import unittest
  4. import joblib
  5. from glob import glob
  6. from dataloaders import neo
  7. from bci_core.feature_extractors import FeatExtractor
  8. from bci_core.model import baseline_model, stacking_riemann, ChannelScaler
  9. import shutil
  10. from sklearn.utils.validation import check_is_fitted, NotFittedError
  11. from sklearn.pipeline import Pipeline
  12. from sklearn.ensemble import StackingClassifier
  13. class TestTraining(unittest.TestCase):
  14. @classmethod
  15. def setUpClass(cls) -> None:
  16. root_path = './tests/data'
  17. sessions = {'cylinder': ['eeg-data/2', 'eeg-data/6'], 'ball': ['eeg-data/4', 'eeg-data/5']}
  18. cls.event_id = {'rest': 0, 'cylinder': 1, 'ball': 2}
  19. raw = neo.raw_preprocessing(root_path, sessions, unify_label=True)
  20. raw.drop_channels(['T3', 'T4', 'A1', 'A2', 'T5', 'T6', 'M1', 'M2', 'Fp1', 'Fp2', 'F7', 'F8', 'O1', 'Oz', 'O2', 'F3', 'F4', 'Fz'])
  21. cls.raw = raw
  22. def test_training_baseline(self):
  23. model = training.train_model(self.raw, self.event_id, model_type='baseline')
  24. check_is_fitted(model)
  25. def test_saver(self):
  26. feat_ext = FeatExtractor(1000, lfb_bands=[(15, 30), [30, 45]], hg_bands=[(55, 95), (105, 145)])
  27. model_riemann = stacking_riemann(12, 12, 1, 1)
  28. model_baseline = baseline_model(1)
  29. scaler = ChannelScaler()
  30. event_id = {'1': 5, '0': 3}
  31. training.model_saver([feat_ext, scaler, model_riemann, model_baseline], './tests/data', 'baseline', 'f77cbe10a8de473992542e9f4e913a66', event_id)
  32. self.assertTrue(os.path.isdir(os.path.join('./tests/data', 'f77cbe10a8de473992542e9f4e913a66')))
  33. model_file = glob(os.path.join('./tests/data',
  34. 'f77cbe10a8de473992542e9f4e913a66',
  35. '*.pkl'))
  36. self.assertEqual(len(model_file), 1)
  37. name = os.path.normpath(model_file[0]).split(os.sep)
  38. class_name, events, date = name[-1].split('_')
  39. print(class_name, events, date)
  40. self.assertTrue(class_name == 'baseline')
  41. self.assertTrue(events == '0+1')
  42. # load model
  43. feat, scaler, model_riem, model_base = joblib.load(model_file[0])
  44. self.assertTrue(isinstance(feat, FeatExtractor))
  45. self.assertTrue(isinstance(scaler, ChannelScaler))
  46. self.assertTrue(isinstance(model_riem, StackingClassifier))
  47. self.assertTrue(isinstance(model_base, Pipeline))
  48. shutil.rmtree(os.path.join('./tests/data', 'f77cbe10a8de473992542e9f4e913a66'))