信号处理--情绪分类数据集DEAP预处理(python版)

2024-03-28 07:44

本文主要是介绍信号处理--情绪分类数据集DEAP预处理(python版),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

关于

DEAP数据集是一个常用的情绪分类公共数据,在日常研究中经常被使用到。如何合理地预处理DEAP数据集,对于后端任务的成功与否,非常重要。本文主要介绍DEAP数据集的预处理流程。

工具

 图片来源:DEAP: A Dataset for Emotion Analysis using Physiological and Audiovisual Signals

 DEAP数据集详细描述:https://www.eecs.qmul.ac.uk/mmv/datasets/deap/doc/tac_special_issue_2011.pdf

方法实现

加载.bdf文件+去除非脑电通道
	bdf_file_name = 's{:02d}.bdf'.format(subject_id)bdf_file_path = os.path.join(root_folder, bdf_file_name)print('Loading .bdf file {}'.format(bdf_file_path))raw = mne.io.read_raw_bdf(bdf_file_path, preload=True, verbose=False).load_data()ch_names = raw.ch_nameseeg_channels = ch_names[:N_EEG_electrodes]non_eeg_channels = ch_names[N_EEG_electrodes:]stim_ch_name = ch_names[-1]stim_channels = [ stim_ch_name ]
设置脑电电极规范
raw_copy = raw.copy()raw_stim = raw_copy.pick_channels(stim_channels)raw.pick_channels(eeg_channels)print('Setting montage with BioSemi32 electrode locations')biosemi_montage = mne.channels.make_standard_montage(kind='biosemi32', head_size=0.095)raw.set_montage(biosemi_montage)
带通滤波器(4-45Hz),陷波滤波器(50Hz)
	print('Applying notch filter (50Hz) and bandpass filter (4-45Hz)')raw.notch_filter(np.arange(50, 251, 50), n_jobs=1, fir_design='firwin')raw.filter(4, 45, fir_design='firwin')
脑电通道相对于均值重标定
	# Average reference. This is normally added by default, but can also be added explicitly.print('Re-referencing all electrodes to the common average reference')raw.set_eeg_reference()
获取事件标签
print('Getting events from the status channel')events = mne.find_events(raw_stim, stim_channel=stim_ch_name, verbose=True)if subject_id<=23:# Subject 1-22 and Subjects 23-28 have 48 channels.# Subjects 29-32 have 49 channels.# For Subjects 1-22 and Subject 23, the stimuli channel has the name 'Status'# For Subjects 24-28, the stimuli channel has the name ''# For Subjects 29-32, the stimuli channels have the names '-0' and '-1'passelse:# The values of the stimuli channel have to be changed for Subjects 24-32# Trigger channel has a non-zero initial value of 1703680 (consider using initial_event=True to detect this event)events[:,2] -= 1703680 # subtracting initial valueevents[:,2] = events[:,2] % 65536 # getting modulo with 65536print('')event_IDs = np.unique(events[:,2])for event_id in event_IDs:col = events[:,2]print('Event ID {} : {:05}'.format(event_id, np.sum( 1.0*(col==event_id) ) ) )
获取事件对应信号
inds_new_trial = np.where(events[:,2] == 4)[0]events_new_trial = events[inds_new_trial,:]baseline = (0, 0)print('Epoching the data, into [-5sec, +60sec] epochs')epochs = mne.Epochs(raw, events_new_trial, event_id=4, tmin=-5.0, tmax=60.0, picks=eeg_channels, baseline=baseline, preload=True)
ICA去除伪迹
print('Fitting ICA to the epoched data, using {} ICA components'.format(N_ICA))ica = ICA(n_components=N_ICA, method='fastica', random_state=23)ica.fit(epochs)ICA_model_file = os.path.join(ICA_models_folder, 's{:02}_ICA_model.pkl'.format(subject_id))with open(ICA_model_file, 'wb') as pkl_file:pickle.dump(ica, pkl_file)# ica.plot_sources(epochs)print('Plotting ICA components')fig = ica.plot_components()cnt = 1for fig_x in fig:print(fig_x)fig_ICA_path = os.path.join(ICA_components_folder, 's{:02}_ICA_components_{}.png'.format(subject_id, cnt))fig_x.savefig(fig_ICA_path)cnt += 1# Inspect frontal channels to check artifact removal # ica.plot_overlay(raw, picks=['Fp1'])# ica.plot_overlay(raw, picks=['Fp2'])# ica.plot_overlay(raw, picks=['AF3'])# ica.plot_overlay(raw, picks=['AF4'])N_excluded_channels = len(ica.exclude)print('Excluding {:02} ICA component(s): {}'.format(N_excluded_channels, ica.exclude))epochs_clean = ica.apply(epochs.copy())#############################print('Plotting PSD of epoched data')fig = epochs_clean.plot_psd(fmin=4, fmax=45, area_mode='range', average=False, picks=eeg_channels, spatial_colors=True)fig_PSD_path = os.path.join(PSD_folder, 's{:02}_PSD.png'.format(subject_id))fig.savefig(fig_PSD_path)print('Saving ICA epoched data as .pkl file')mneraw_pkl_path = os.path.join(mneraw_as_pkl_folder, 's{:02}.pkl'.format(subject_id))with open(mneraw_pkl_path, 'wb') as pkl_file:pickle.dump(epochs_clean, pkl_file)epochs_clean_copy = epochs_clean.copy()
数据降采样和保存
print('Downsampling epoched data to 128Hz')epochs_clean_downsampled = epochs_clean_copy.resample(sfreq=128.0)print('Plotting PSD of epoched downsampled data')fig = epochs_clean_downsampled.plot_psd(fmin=4, fmax=45, area_mode='range', average=False, picks=eeg_channels, spatial_colors=True)fig_PSD_path = os.path.join(PSD_folder, 's{:02}_PSD_downsampled.png'.format(subject_id))fig.savefig(fig_PSD_path)data = epochs_clean.get_data()data_downsampled = epochs_clean_downsampled.get_data()print('Original epoched data shape: {}'.format(data.shape))print('Downsampled epoched data shape: {}'.format(data_downsampled.shape))###########################################EEG_channels_table = pd.read_excel(DEAP_EEG_channels_xlsx_path)EEG_channels_geneva = EEG_channels_table['Channel_name_Geneva'].valueschannel_pick_indices = []print('\nPreparing EEG channel reordering to comply with the Geneva order')for (geneva_ch_index, geneva_ch_name) in zip(range(N_EEG_electrodes), EEG_channels_geneva):bdf_ch_index = eeg_channels.index(geneva_ch_name)channel_pick_indices.append(bdf_ch_index)print('Picking source (raw) channel #{:02} to fill target (npy) channel #{:02} | Electrode position: {}'.format(bdf_ch_index + 1, geneva_ch_index + 1, geneva_ch_name))ratings = pd.read_csv(ratings_csv_path)is_subject =  (ratings['Participant_id'] == subject_id)ratings_subj = ratings[is_subject]trial_pick_indices = []print('\nPreparing EEG trial reordering, from presentation order, to video (Experiment_id) order')for i in range(N_trials):exp_id = i+1is_exp = (ratings['Experiment_id'] == exp_id)trial_id = ratings_subj[is_exp]['Trial'].values[0]trial_pick_indices.append(trial_id - 1)print('Picking source (raw) trial #{:02} to fill target (npy) trial #{:02} | Experiment_id: {:02}'.format(trial_id, exp_id, exp_id))# Store clean and reordered data to numpy arrayepoch_duration = data_downsampled.shape[-1]data_npy = np.zeros((N_trials, N_EEG_electrodes, epoch_duration))print('\nStoring the final EEG data in a numpy array of shape {}'.format(data_npy.shape))for trial_source, trial_target in zip(trial_pick_indices, range(N_trials)):data_trial = data_downsampled[trial_source]data_trial_reordered_channels = data_trial[channel_pick_indices,:]data_npy[trial_target,:,:] = data_trial_reordered_channels.copy()print('Saving the final EEG data in a .npy file')np.save(npy_path, data_npy)print('Raw EEG has been filtered, common average referenced, epoched, artifact-rejected, downsampled, trial-reordered and channel-reordered.')print('Finished.')

图片来源: Blog - Ayan's Blog

代码获取

后台私信,请注明文章名称;

相关项目和代码问题,欢迎交流。

这篇关于信号处理--情绪分类数据集DEAP预处理(python版)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/854927

相关文章

Python判断for循环最后一次的6种方法

《Python判断for循环最后一次的6种方法》在Python中,通常我们不会直接判断for循环是否正在执行最后一次迭代,因为Python的for循环是基于可迭代对象的,它不知道也不关心迭代的内部状态... 目录1.使用enuhttp://www.chinasem.cnmerate()和len()来判断for

C#提取PDF表单数据的实现流程

《C#提取PDF表单数据的实现流程》PDF表单是一种常见的数据收集工具,广泛应用于调查问卷、业务合同等场景,凭借出色的跨平台兼容性和标准化特点,PDF表单在各行各业中得到了广泛应用,本文将探讨如何使用... 目录引言使用工具C# 提取多个PDF表单域的数据C# 提取特定PDF表单域的数据引言PDF表单是一

使用Python实现高效的端口扫描器

《使用Python实现高效的端口扫描器》在网络安全领域,端口扫描是一项基本而重要的技能,通过端口扫描,可以发现目标主机上开放的服务和端口,这对于安全评估、渗透测试等有着不可忽视的作用,本文将介绍如何使... 目录1. 端口扫描的基本原理2. 使用python实现端口扫描2.1 安装必要的库2.2 编写端口扫

使用Python实现操作mongodb详解

《使用Python实现操作mongodb详解》这篇文章主要为大家详细介绍了使用Python实现操作mongodb的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、示例二、常用指令三、遇到的问题一、示例from pymongo import MongoClientf

使用Python合并 Excel单元格指定行列或单元格范围

《使用Python合并Excel单元格指定行列或单元格范围》合并Excel单元格是Excel数据处理和表格设计中的一项常用操作,本文将介绍如何通过Python合并Excel中的指定行列或单... 目录python Excel库安装Python合并Excel 中的指定行Python合并Excel 中的指定列P

一文详解Python中数据清洗与处理的常用方法

《一文详解Python中数据清洗与处理的常用方法》在数据处理与分析过程中,缺失值、重复值、异常值等问题是常见的挑战,本文总结了多种数据清洗与处理方法,文中的示例代码简洁易懂,有需要的小伙伴可以参考下... 目录缺失值处理重复值处理异常值处理数据类型转换文本清洗数据分组统计数据分箱数据标准化在数据处理与分析过

大数据小内存排序问题如何巧妙解决

《大数据小内存排序问题如何巧妙解决》文章介绍了大数据小内存排序的三种方法:数据库排序、分治法和位图法,数据库排序简单但速度慢,对设备要求高;分治法高效但实现复杂;位图法可读性差,但存储空间受限... 目录三种方法:方法概要数据库排序(http://www.chinasem.cn对数据库设备要求较高)分治法(常

Python调用另一个py文件并传递参数常见的方法及其应用场景

《Python调用另一个py文件并传递参数常见的方法及其应用场景》:本文主要介绍在Python中调用另一个py文件并传递参数的几种常见方法,包括使用import语句、exec函数、subproce... 目录前言1. 使用import语句1.1 基本用法1.2 导入特定函数1.3 处理文件路径2. 使用ex

Python脚本实现自动删除C盘临时文件夹

《Python脚本实现自动删除C盘临时文件夹》在日常使用电脑的过程中,临时文件夹往往会积累大量的无用数据,占用宝贵的磁盘空间,下面我们就来看看Python如何通过脚本实现自动删除C盘临时文件夹吧... 目录一、准备工作二、python脚本编写三、脚本解析四、运行脚本五、案例演示六、注意事项七、总结在日常使用

Python将大量遥感数据的值缩放指定倍数的方法(推荐)

《Python将大量遥感数据的值缩放指定倍数的方法(推荐)》本文介绍基于Python中的gdal模块,批量读取大量多波段遥感影像文件,分别对各波段数据加以数值处理,并将所得处理后数据保存为新的遥感影像... 本文介绍基于python中的gdal模块,批量读取大量多波段遥感影像文件,分别对各波段数据加以数值处