2
0

online_sim.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. '''
  2. 模型模拟在线测试脚本
  3. 在线模式测试:event f1-score and decision trace
  4. '''
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. import mne
  8. import yaml
  9. import os
  10. import argparse
  11. import logging
  12. from sklearn.metrics import accuracy_score
  13. from dataloaders import neo
  14. import bci_core.online as online
  15. import bci_core.utils as bci_utils
  16. import bci_core.viz as bci_viz
  17. from settings.config import settings
  18. logging.basicConfig(level=logging.DEBUG)
  19. logger = logging.getLogger(__name__)
  20. config_info = settings.CONFIG_INFO
  21. def parse_args():
  22. parser = argparse.ArgumentParser(
  23. description='Model validation'
  24. )
  25. parser.add_argument(
  26. '--subj',
  27. dest='subj',
  28. help='Subject name',
  29. default=None,
  30. type=str
  31. )
  32. parser.add_argument(
  33. '--state-change-threshold',
  34. '-scth',
  35. dest='state_change_threshold',
  36. help='Threshold for HMM state change',
  37. default=0.75,
  38. type=float
  39. )
  40. parser.add_argument(
  41. '--state-trans-prob',
  42. '-stp',
  43. dest='state_trans_prob',
  44. help='Transition probability for HMM state change',
  45. default=0.8,
  46. type=float
  47. )
  48. parser.add_argument(
  49. '--momentum',
  50. help='Probability update momentum',
  51. default=0.5,
  52. type=float
  53. )
  54. parser.add_argument(
  55. '--model-filename',
  56. dest='model_filename',
  57. help='Model filename',
  58. default=None,
  59. type=str
  60. )
  61. return parser.parse_args()
  62. class DataGenerator:
  63. def __init__(self, fs, X, epoch_step=1.):
  64. self.fs = int(fs)
  65. self.X = X
  66. self.epoch_step = epoch_step
  67. def get_data_batch(self, current_index):
  68. # return epoch_step length batch
  69. # create mne object
  70. ind = int(self.epoch_step * self.fs)
  71. data = self.X[:, current_index - ind:current_index].copy()
  72. return self.fs, [], data
  73. def loop(self, step_size=0.1):
  74. step = int(step_size * self.fs)
  75. for i in range(int(self.epoch_step * self.fs), self.X.shape[1] + 1, step):
  76. yield i / self.fs, self.get_data_batch(i)
  77. @property
  78. def time_range(self):
  79. return self.epoch_step, self.X.shape[1] / self.fs
  80. def time_steps(self, step_size=0.1):
  81. step = int(step_size * self.fs)
  82. return len(list(range(int(self.epoch_step * self.fs), self.X.shape[1] + 1, step)))
  83. def _evaluation_loop(raw, events, model_hmm, epoch_length, step_length, event_trial_length):
  84. val_data = raw.get_data()
  85. fs = raw.info['sfreq']
  86. data_gen = DataGenerator(fs, val_data, epoch_step=epoch_length)
  87. # events -> 1 / step_length
  88. events[:, 0] = (events[:, 0] / fs / step_length).astype(np.int32)
  89. decision_with_hmm = []
  90. decision_without_hmm = []
  91. probs = []
  92. probs_naive = []
  93. for time, (fs, event, data) in data_gen.loop(step_length):
  94. step_p, cls = model_hmm.viterbi(fs, data, return_step_p=True)
  95. if cls >=0:
  96. cls = model_hmm.model.classes_[cls]
  97. decision_with_hmm.append((time, cls)) # map to unified label
  98. decision_without_hmm.append((time, model_hmm.model.classes_[np.argmax(step_p)]))
  99. probs.append(model_hmm.probability)
  100. probs_naive.append(step_p)
  101. probs = np.array(probs)
  102. probs_naive = np.array(probs_naive)
  103. events_pred = _construct_model_event(decision_with_hmm, 1 / step_length)
  104. events_pred_naive = _construct_model_event(decision_without_hmm, 1 / step_length)
  105. p_hmm, r_hmm, f1_hmm = bci_utils.event_metric(event_true=events, event_pred=events_pred, fs=fs)
  106. p_n, r_n, f1_n = bci_utils.event_metric(events, events_pred_naive, fs=fs)
  107. time_steps = data_gen.time_steps(step_length)
  108. start_ind = int(data_gen.time_range[0] / step_length)
  109. stim_true = bci_utils.event_to_stim_channel(events, time_steps, trial_length=int(event_trial_length / step_length), start_ind=start_ind)
  110. stim_pred = bci_utils.event_to_stim_channel(events_pred, time_steps, start_ind=start_ind)
  111. stim_pred_naive = bci_utils.event_to_stim_channel(events_pred_naive, time_steps, start_ind=start_ind)
  112. accu_hmm = accuracy_score(stim_true, stim_pred)
  113. accu_naive = accuracy_score(stim_true, stim_pred_naive)
  114. # hmm plot
  115. fig_hmm, axes = plt.subplots(model_hmm.n_classes + 2, 1, sharex=True, figsize=(10, 8))
  116. axes[0].set_title('True states')
  117. bci_viz.plot_states(data_gen.time_range, stim_true, ax=axes[0])
  118. axes[1].set_title('State sequence')
  119. bci_viz.plot_states(data_gen.time_range, stim_pred, ax=axes[1])
  120. for i, ax in enumerate(axes[2:]):
  121. bci_viz.plot_state_prob_with_cue(data_gen.time_range, stim_true, probs[:, i], ax=ax)
  122. fig_hmm.suptitle('With HMM')
  123. # naive plot
  124. fig_naive, axes = plt.subplots(model_hmm.n_classes + 2, 1, sharex=True, sharey=True, figsize=(10, 8))
  125. axes[0].set_title('True states')
  126. bci_viz.plot_states(data_gen.time_range, stim_true, ax=axes[0])
  127. axes[1].set_title('State sequence')
  128. bci_viz.plot_states(data_gen.time_range, stim_pred_naive, ax=axes[1])
  129. for i, ax in enumerate(axes[2:]):
  130. bci_viz.plot_state_prob_with_cue(data_gen.time_range, stim_true, probs_naive[:, i], ax=ax)
  131. fig_naive.suptitle('Naive')
  132. return (fig_hmm, fig_naive), (p_hmm, r_hmm, f1_hmm, accu_hmm), (p_n, r_n, f1_n, accu_naive)
  133. def simulation(raw_val, event_id, model,
  134. epoch_length=1.,
  135. step_length=0.1,
  136. event_trial_length=5.):
  137. """模型验证接口,使用指定数据进行验证,绘制ersd map
  138. Args:
  139. raw (mne.io.Raw)
  140. event_id (dict)
  141. model: validate existing model,
  142. epoch_length (float): batch data length, default 1 (s)
  143. step_length (float): data step length, default 0.1 (s)
  144. event_trial_length (float):
  145. Returns:
  146. None
  147. """
  148. fs = raw_val.info['sfreq']
  149. events_val, _ = mne.events_from_annotations(raw_val, event_id)
  150. # run with and without hmm
  151. fig_pred, metric_hmm, metric_naive = _evaluation_loop(raw_val,
  152. events_val,
  153. model,
  154. epoch_length,
  155. step_length,
  156. event_trial_length=event_trial_length)
  157. return metric_hmm, metric_naive, fig_pred
  158. def _construct_model_event(decision_seq, fs, start_cond=0):
  159. def _filter_seq(decision_seq):
  160. new_seq = [(decision_seq[0][0], start_cond)]
  161. for i in range(1, len(decision_seq)):
  162. if decision_seq[i][1] == -1:
  163. new_seq.append((decision_seq[i][0], new_seq[-1][1]))
  164. else:
  165. new_seq.append(decision_seq[i])
  166. return new_seq
  167. decision_seq = _filter_seq(decision_seq)
  168. last_state = decision_seq[0][1]
  169. events = [(int(decision_seq[0][0] * fs), 0, last_state)]
  170. for i in range(1, len(decision_seq)):
  171. time, label = decision_seq[i]
  172. if label != last_state:
  173. last_state = label
  174. events.append([int(time * fs), 0, label])
  175. return np.array(events)
  176. if __name__ == '__main__':
  177. args = parse_args()
  178. subj_name = args.subj
  179. data_dir = os.path.join(settings.DATA_PATH, subj_name)
  180. model_path = os.path.join(settings.MODEL_PATH, subj_name, args.model_filename)
  181. with open(os.path.join(data_dir, 'val_info.yml'), 'r') as f:
  182. info = yaml.safe_load(f)
  183. sessions = info['sessions']
  184. # preprocess raw
  185. trial_time = 5.
  186. raw, event_id = neo.raw_loader(data_dir, sessions,
  187. reref_method=config_info['reref'],
  188. ori_epoch_length=trial_time,
  189. upsampled_epoch_length=None)
  190. # load model
  191. input_kwargs = {
  192. 'state_trans_prob': args.state_trans_prob,
  193. 'state_change_threshold': args.state_change_threshold,
  194. 'momentum': args.momentum
  195. }
  196. model_hmm = online.model_loader(model_path, **input_kwargs)
  197. # do online simulation
  198. metric_hmm, metric_naive, fig_pred = simulation(raw,
  199. event_id,
  200. model=model_hmm,
  201. epoch_length=config_info['buffer_length'],
  202. step_length=0.1,
  203. event_trial_length=trial_time)
  204. fig_pred[0].savefig(os.path.join(data_dir, 'pred_hmm.pdf'))
  205. fig_pred[1].savefig(os.path.join(data_dir, 'pred_naive.pdf'))
  206. logger.info(f'With HMM: precision: {metric_hmm[0]:.4f}, recall: {metric_hmm[1]:.4f}, f1_score: {metric_hmm[2]:.4f}, accuracy: {metric_hmm[3]:.4f}')
  207. logger.info(f'Without HMM: precision: {metric_naive[0]:.4f}, recall: {metric_naive[1]:.4f}, f1_score: {metric_naive[2]:.4f}, accuracy: {metric_naive[3]:.4f}')
  208. plt.show()