Добавил:
kiopkiopkiop18@yandex.ru Вовсе не секретарь, но почту проверяю Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

5 курс / ОЗИЗО Общественное здоровье и здравоохранение / Проектирование_мультимодальных_интерфейсов_мозг_компьютер

.pdf
Скачиваний:
1
Добавлен:
24.03.2024
Размер:
10.34 Mб
Скачать

Разработка функций

ax1.set(ylabel='µV²/Hz (dB)') ax2.legend(ax2.lines[2::3], stages)

В результаты получим график с параметрами, как на рис. 61. Получим следующий результат в командной строке:

Loading data for 58 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Averaging across epochs…

Loading data for 250 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Averaging across epochs…

Loading data for 220 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Averaging across epochs…

Loading data for 125 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Averaging across epochs…

Loading data for 188 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Averaging across epochs…

Loading data for 109 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Averaging across epochs…

Loading data for 562 events and 3000 original time points …

119

Рекомендовано к покупке и изучению сайтом МедУнивер - https://meduniver.com/

Глава 6. Мультимодальная обработка сигналов на примере данных полисомнографии

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Averaging across epochs…

Loading data for 105 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Averaging across epochs…

Loading data for 170 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Averaging across epochs…

Loading data for 157 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows Averaging across epochs…

Преобразователь на основе scikit-­learn   из функции Python

Теперь создадим функцию для извлечения характеристик ЭЭГ на основе относительной мощности в определенных частотных диапазонах, чтобы иметь возможность прогнозировать стадии сна по сигналам ЭЭГ.

def eeg_power_band(epochs):

"""EEG relative power band feature extraction.

Эта функция берет объект mne.Epochs и создает характеристики ЭЭГ на основе относительной мощности в определенных частотных диапазонах, совместимых со scikit-­learn.

Parameters

----------

epochs: Epochs The data.

Returns

120

Создание процесса мультиклассовой классификации с использованием scikit-­learn

--------

X: numpy array of shape [n_samples, 5] Transformed data.

"""

# specific frequency bands FREQ_BANDS = {"delta": [0.5, 4.5],

"theta": [4.5, 8.5], "alpha": [8.5, 11.5], "sigma": [11.5, 15.5], "beta": [15.5, 30]}

spectrum = epochs.compute_psd(picks='eeg', fmin=0.5, fmax=30.)

psds, freqs = spectrum.get_data(return_freqs=True)

# Normalize the PSDs

psds /= np.sum(psds, axis= –1, keepdims=True)

X = []

for fmin, fmax in FREQ_BANDS.values():

psds_band = psds[:,:, (freqs >= fmin) & (freqs < fmax)].mean(axis= –1)

X.append(psds_band.reshape(len(psds), –1)) return np.concatenate(X, axis=1)

Создание процесса мультиклассовой классификации с использованием scikit-­learn

Чтобы ответить на вопрос, насколько хорошо мы можем предсказать стадии сна Боба по данным Алисы, и избежать как можно больше шаблонных кодов, воспользуемся двумя ключевыми функциями sckit-­learn: Pipeline и FunctionTransformer.

pipe = make_pipeline(FunctionTransformer(eeg_power_ band, validate=False),

RandomForestClassifier(n_estimators=100, random_ state=42))

# Train

y_train = epochs_train.events[:, 2] pipe.fit(epochs_train, y_train)

# Test

121

Рекомендовано к покупке и изучению сайтом МедУнивер - https://meduniver.com/

Глава 6. Мультимодальная обработка сигналов на примере данных полисомнографии

y_pred = pipe.predict(epochs_test)

# Assess the results

y_test = epochs_test.events[:, 2] acc = accuracy_score(y_test, y_pred)

print("Accuracy score: {}".format(acc))

Loading data for 841 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Loading data for 1103 events and 3000 original time points …

0 bad epochs dropped

Using multitaper spectrum estimation with 7 DPSS windows

Accuracy score: 0.6727107887579329

В итоге можно сделать следующий вывод: мы можем предсказать стадии сна Боба на основе данных Алисы с точностью 0.67.

Дальнейший анализ данных

Можем проверить матрицу ошибок и отчет о точности классификации по метрике accuracy для разных этапов полисомнограммы.

print(confusion_matrix(y_test, y_pred))

 

 

[[155 0 0 2 0]

 

 

 

 

 

[79 5 3 1 21]

50]

 

 

 

 

[80

19 389

24

 

 

 

 

[0

0

4 101

0]

 

 

 

 

 

[53 5 19 1 92]]

 

 

 

 

print(classification_report(y_test, y_pred, target_

names=event_id.keys()))

 

 

 

 

 

 

 

 

precision recall f1 score support

Sleep stage W

 

0.42

0.99

0.59

157

Sleep stage 1

 

0.17

0.05

0.07

109

Sleep stage 2

 

0.94

0.69

0.80

562

Sleep stage 3/4

0.78

0.96

0.86

105

Sleep stage R

 

0.56

0.54

0.55

170

accuracy

 

 

 

 

0.67

1103

122

Задания к главе 6

macro avg

0.58

0.65

0.58

1103

weighted avg

0.72

0.67

0.66

1103

Таким образом, мы использовали простые и эффективные инструменты scikit-­learn и MNE для выполнения временной классификации стадий сна из мультимодальных и многомерных временных рядов. Используемая модель объединяет информацию от разных датчиков благодаря операции линейной пространственной фильтрации и строит иерархическое представление признаков данных PSG. Кроме того, она позволяет объединять информацию источников биомедицинских сигналов разных модальностей, обрабатываемых отдельными конвейерами. Такой подход демонстрирует довольно высокие метрики классификации при небольшом времени выполнения и вычислительных затратах. Это делает подход хорошим кандидатом для использования в портативном устройстве и для онлайн-­классификации стадий сна с помощью ИМК.

Задания к главе 6

1.Выберите 50 других субъектов из базы данных Physionet и выполните 5 кратную перекрестную проверку, каждый раз оставляя 10 субъектов в наборе тестов (URL: https://physionet.org/physiobank/ database/sleep-edfx/sleep-cassette/).

2.Попробуйте применить для классификации нейронную сеть, как было рассмотрено в главе 5. Далее попробуйте увеличить сложность сети. Это может включать в себя больше слоев, больше нейронов, больше входных данных или измененные гиперпараметры (напри-

мер, изменение скорости обучения, тестирование различных функций активации! или добавление сверточных слоев).

Последствием повышения сложности сети является то, что сети может потребоваться значительно больше данных для обучения. Кроме того, увеличение скорости обучения может привести к нежелательным результатам.

3.Увеличьте количество данных, на которых сеть тренируется. В интернете доступно множество бесплатных наборов данных, которые предоставляют ряд различных типов данных. Вот несколько вариантов открытых баз данных сигналов:

123

Рекомендовано к покупке и изучению сайтом МедУнивер - https://meduniver.com/

Глава 6. Мультимодальная обработка сигналов на примере данных полисомнографии

URL: https://ieee-dataport.org/documents/event-related-potentials- p300 eeg-bci- dataset

URL: http://predict.cs.unm.edu/

URL: http://moabb.neurotechx.com/docs/index.html (совместимые с MNE-Python наборы данных).

4. Поэкспериментируйте на этих данных с известными методами машинного обучения, например:

линейным дискриминантным анализом (Linear discriminant analysis, LDA),

методом опорных векторов (Support vector machine, SVM),

методом ближайших соседей (K-nearest neighbors algorithm, k-NN),

байесовским классификатором (Bayesian classifier, BC),

деревьями решений (Decision trees, DT),

глубокими нейронными сетями (Deep learning, DL).

124

Список библиографических ссылок

1.Технология. Интерфейс «мозг-компьютер». URL: https://dfnc. ru/arhiv-zhurnalov/2022–4–75/tehnologiya-interfejs-mozg-kompyuter/ (дата обращения: 26.12.2022).

2.Milan J. del R., Carmena J. Invasive or Noninvasive: Understanding Brain-­Machine Interface Technology Conversations in BME // IEEE Engineering in Medicine and Biology Magazine. 2010. Vol. 29, N 1. Pp. 16–22.

3.Les interfaces Cerveau-­Machine pour la palliation du handicap moteur sévère / M. Bekaert [et al.] // Sciences et Technologies pour le Handicap. 2009. Vol. 3, N 1. Pp. 95–121.

4.Deep Learning Algorithm for Brain-­Computer Interface / A. Mansoor [et al.] // Scientific Programming. 2020. Vol. 2020. Pp. 1–12.

5.A Review of EEG-Based Brain-­Computer Interface Systems Design / W. Zhang [et al.] // Brain Science Advances. 2018. Vol. 4, N 2. Pp. 156–167.

6.Roman-­Gonzalez A. EEG Signal Processing for BCI Applications // Human — Computer Systems Interaction: Backgrounds and Applications 2: Advances in Intelligent and Soft Computing / coll. J. Kacprzyk ; eds. Z. S. Hippe, J. L. Kulikowski, T. Mroczek. Berlin, Heidelberg : Springer Berlin Heidelberg, 2012. Vol. 98. Pp. 571–591.

7.Multimodal Architecture and Interfaces. URL: https://www.w3.org/ TR/mmi-arch/ (дата обращения: 17.08.2017).

8.Syskov A. M., Borisov V. I., Kublanov V. S. Intelligent multimodal user interface for telemedicine application // 2017 25th Telecommunication Forum (TelFOR). 2017. Pp. 1–4.

9.Borisov V., Syskov A., Kublanov V. Functional state assessment of an athlete by means of the brain-­computer interface multimodal metrics // IFMBE Proceedings. 2019. Vol. 68. Pp. 71–75.

10.Case study of interrelation between brain-­computer interface based multimodal metric and heart rate variability / V. S. Vasilyev [et al.] // HEALTHINF 2019–12th International Conference on Health Informatics, Proceed-

125

Рекомендовано к покупке и изучению сайтом МедУнивер - https://meduniver.com/

Список библиографических ссылок

ings; Part of 12th International Joint Conference on Biomedical Engineering Systems and Technologies, BIOSTEC 2019. 2019. Pp. 532–538.

11.Vasilyev V., Borisov V., Syskov A. Biofeedback Methodology: A Narrative Review // SIBIRCON 2019 — International Multi-­Conference on Engineering, Computer and Information Sciences, Proceedings. 2019. Pp. 11–16.

12.Peper E., Shaffer F. Biofeedback History: An Alternative View // Biofeedback. 2010. Vol. 38, N 4. Pp. 142–147.

13.Kos A., Tomažič S., Umek A. Suitability of Smartphone Inertial Sensors for Real-­Time Biofeedback Applications // Sensors. 2016. Vol. 16, N 3. P. 301.

14.Mobile Biofeedback Therapy for the Treatment of Panic Attacks: A Pilot Feasibility Study / R. S. McGinnis [et al.] // 2019 IEEE 16th International Conference on Wearable and Implantable Body Sensor Networks (BSN). 2019. Pp. 1–4.

15.Rehabilitation Biofeedback Using EMG Signal Based on Android Platform / M. Yassin [et al.] // 2017 IEEE 30th International Symposium on Computer-­Based Medical Systems (CBMS). 2017. Pp. 475–480.

16.Biofeedback in the Wild — A SmartWatch Approach / N. Pilgram [et al.] // 2018 IEEE International Conference on Pervasive Computing and Communications Workshops (PerCom Workshops). 2018. Pp. 312–317.

17.Peake J.M., Kerr G., Sullivan J. P. A Critical Review of Consumer Wearables, Mobile Applications, and Equipment for Providing Biofeedback, Monitoring Stress, and Sleep in Physically Active Populations // Frontiers in Physiology. 2018. Vol. 9. Pp. 47–48.

18.Using Accelerometer and Gyroscopic Measures to Quantify Postural Stability / J. L. Alberts [et al.] // Journal of Athletic Training. 2015. Vol. 50, N 6. Pp. 578–588.

19.Standing balance assessment using a head-mounted wearable device / J. P. Salisbury [et al.]. // Bioengineering. 2017. [S. p.].

20.Smart Gait-­Aid Glasses for Parkinson's Disease Patients / D. Ahn [et al.] // IEEE Transactions on Biomedical Engineering. 2017. Vol. 64, N 10. Pp. 2394–2402.

21.Mobile brain-­computer interface application for mental status evaluation / V. Borisov [et al.] // Proceedings — 2017 International Multi-­ Conference on Engineering, Computer and Information Sciences, SIBIRCON 2017. Pp. 550–555.

22.Kos A. Umek A. Biomechanical Biofeedback Systems and Applications: Human–Computer Interaction Series. [Berlin] : Springer International Publishing, 2018. [S. p.].

126

Список библиографических ссылок

23.Li R. Lai D.T.H. Lee W. A Survey on Biofeedback and Actuation in Wireless Body Area Networks (WBANs) // IEEE Reviews in Biomedical Engineering. 2017. Vol. 10. Pp. 162–173.

24.Hunkin H., King D. L., Zajac I. T. Wearable devices as adjuncts in the treatment of anxiety-­related symptoms: A narrative review of five device modalities and implications for clinical practice // Clinical Psychology: Science and Practice. 2019. Vol. 0, N 0. P. e12290.

25.Mason S.G., Birch G. E. A general framework for brain-­computer interface design // IEEE Transactions on Neural Systems and Rehabilitation Engineering. 2003. Vol. 11, N 1. Pp. 70–85.

26.Easttom C. BCI glossary and functional model by the IEEE P2731 working group // Brain-­Computer Interfaces. 2021. Vol. 8, N 3. Pp. 39–41.

27.Wolpaw J. R., Millán J. del R., Ramsey N. F. Chap. 2. Brain-comput- er interfaces: Definitions and principles // Handbook of Clinical Neurology: Brain-­Computer Interfaces / eds. N. F. Ramsey, J. del R. Millán. Elsevier. 2020. Vol. 168. Chapter 2 — Brain-computer interfaces. Pp. 15–23.

28.TiD-Introducing and Benchmarking an Event-­Delivery System for Brain-­Computer Interfaces / C. Breitwieser [et al.] // IEEE transactions on neural systems and rehabilitation engineering: a publication of the IEEE Engineering in Medicine and Biology Society. 2017. Vol. 25, N 12. Pp. 2249–2257.

29.Consensus on the reporting and experimental design of clinical and cognitive-­behavioural neurofeedback studies (CRED-nf checklist) / T. Ros [et al.] // Brain: A Journal of Neurology. 2020. Vol. 143, N 6. Pp. 1674–1685.

30.Proposing a standardized protocol for raw biosignal transmission / C. Breitwieser [et al.] // IEEE transactions on bio-medical engineering. 2012. Vol. 59, N 3. Pp. 852–859.

31.A Functional BCI Model by the P2731 working group: Physiology / A. Hossaini [et al.] // Brain-­Computer Interfaces. 2021. Vol. 8. A Functional BCI Model by the P2731 working group, N 3. Pp. 54–81.

32.A Functional Model for Unifying Brain Computer Interface Terminology / C. Easttom [et al.] // IEEE Open Journal of Engineering in Medicine and Biology. 2021. N 2. Pp. 5–8.

33.Vallabhaneni A. Wang T. He B. Brain — Computer Interface // Neural Engineering: Bioelectric Engineering / ed. B. He. Boston, MA : Springer US, 2005. Pp. 85–121.

34.Performances Evaluation and Optimization of Brain Computer Interface Systems in a Copy Spelling Task / L. Bianchi [et al.] // IEEE Trans-

127

Рекомендовано к покупке и изучению сайтом МедУнивер - https://meduniver.com/

Список библиографических ссылок

actions on Neural Systems and Rehabilitation Engineering. 2007. Vol. 15, N 2. Pp. 207–216.

35.Noninvasive neuroimaging enhances continuous neural tracking for robotic device control / B. J. Edelman [et al.] // Science Robotics. 2019. Vol. 4, N 31. P. eaaw6844.

36.Wolpaw J. Wolpaw E. W. Brain-­Computer Interfaces: Principles and Practice. Brain-­Computer Interfaces. Oxford : University Press, 2012. 420 p. Google-Books-ID: tC2UzuC_WBQC.

37.Discriminative Feature Extraction via Multivariate Linear Regression for SSVEP-Based BCI / H. Wang [et al.] // IEEE transactions on neural systems and rehabilitation engineering: a publication of the IEEE Engineering in Medicine and Biology Society. 2016. Vol. 24, N 5. Pp. 532–541.

38.Congedo M., Barachant A., Bhatia R. Riemannian geometry for EEG-based brain-­computer interfaces; a primer and a review // Brain-­ Computer Interfaces. 2017. Vol. 4, N 3. Pp. 155–174.

39.A review of classification algorithms for EEG-based brain–computer interfaces: a 10 year update / F. Lotte [et al.] // Journal of Neural Engineering. 2018. Vol. 15, N 3. P. 031005.

40.Alter G. Gonzalez R. Responsible practices for data sharing // The American Psychologist. 2018. Vol. 73, N 2. Pp. 146–156.

41.Implementation and relevance of FAIR data principles in biopharmaceutical R&D / J. Wise [et al.] // Drug Discovery Today. 2019. Vol. 24, N 4. Pp. 933–938.

42.Кропотов Д. Ю. Количественная ЭЭГ, когнитивные вызванные потенциалы мозга человека и нейротерапия. Донецк : Заславский А. Ю., 2010. 512 с.

43.Emotiv BCI — Built for Insight and Epoc+ headsets. URL: https://www.emotiv.com/emotiv-bci/ (дата обращения: 23.08.2020).

44.Report of the committee on methods of clinical examination in electroencephalography: 1957 // Electroencephalography and Clinical Neurophysiology. 1958. Vol. 10, N 2. Pp. 370–375.

45.Биомедицинские сигналы и изображения в цифровом здравоохранении: хранение, обработка и анализ : учеб. пособие / В. С. Кубланов [et al.]. Екатеринбург : Изд-во Урал. ун-та, 2020. Accepted: 2020–05–14T08:10:51Z.

46.MNE — MNE 1.0.3 documentation. URL: https://mne.tools/stable/index.html (дата обращения: 30.07.2022).

128