信号处理--情绪分类数据集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

代码获取

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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/775579.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【深度学习】深度学习md笔记总结第2篇:TensorFlow介绍,学习目标【附代码文档】

深度学习笔记完整教程&#xff08;附代码资料&#xff09;主要内容讲述&#xff1a;深度学习课程&#xff0c;深度学习介绍要求,目标,学习目标,1.1.1 区别,学习目标,学习目标。TensorFlow介绍&#xff0c;2.4 张量学习目标,2.4.1 张量(Tensor),2.4.2 创建张量的指令,2.4.3 张量…

02.percona Toolkit工具pt-archiver命令实践

1.命令作用 Percona Toolkit有的32个命令&#xff0c;可以分为7大类 工具类别 工具命令 工具作用 备注 开发类 pt-duplicate-key-checker 列出并删除重复的索引和外键 pt-online-schema-change 在线修改表结构 pt-query-advisor 分析查询语句&#xff0c;并给出建议&#x…

Lua热更新(xlua)

发现错误时检查是否:冒号调用 只需要导入asset文件夹下的Plugins和Xlua这两个文件即可,别的不用导入 生成代码 和清空代码 C#调用lua using Xlua; 需要引入命名空间 解析器里面执行lua语法 lua解析器 LuaEnv 单引号是为了避免引号冲突 第二个参数是报错时显示什么提示…

【Java程序设计】【C00389】基于(JavaWeb)Springboot的校园疫情防控系统(有论文)

基于&#xff08;JavaWeb&#xff09;Springboot的校园疫情防控系统&#xff08;有论文&#xff09; 项目简介项目获取开发环境项目技术运行截图 博主介绍&#xff1a;java高级开发&#xff0c;从事互联网行业六年&#xff0c;已经做了六年的毕业设计程序开发&#xff0c;开发过…

H5小程序视频方案解决方案,实现轻量化视频制作

对于许多企业而言&#xff0c;制作高质量的视频仍然是一个技术门槛高、成本高昂的挑战。针对这一痛点&#xff0c;美摄科技凭借其深厚的技术积累和创新能力&#xff0c;推出了面向企业的H5/小程序视频方案解决方案&#xff0c;为企业提供了一种轻量化、高效、便捷的视频制作方式…

蓝桥杯基础练习汇总详细解析(三)——字母图形、01字符串、闰年判断(详细解题思路、代码实现、Python)

试题 基础练习 字母图形 提交此题 评测记录 资源限制 内存限制&#xff1a;256.0MB C/C时间限制&#xff1a;1.0s Java时间限制&#xff1a;3.0s Python时间限制&#xff1a;5.0s 问题描述 利用字母可以组成一些美丽的图形&#xff0c;下面给出了一个例子&#…

2024年腾讯云4核8G服务器多少钱一年?买1年送3个月

2024年腾讯云4核8G服务器租用优惠价格&#xff1a;轻量应用服务器4核8G12M带宽646元15个月&#xff0c;CVM云服务器S5实例优惠价格1437.24元买一年送3个月&#xff0c;腾讯云4核8G服务器活动页面 txybk.com/go/txy 活动链接打开如下图&#xff1a; 腾讯云4核8G服务器优惠价格 轻…

软件部署资源计算工具:精确评估资源需求

软件部署资源计算工具&#xff1a;精确评估资源需求 在当今快速发展的信息技术时代&#xff0c;软件部署已成为企业运营不可或缺的一部分。然而&#xff0c;一个常见的挑战是如何精确评估软件部署所需的资源。资源评估不仅关系到软件的性能和稳定性&#xff0c;还直接影响到成…

Ps:通道混合器(工作原理篇)

通过通道混合器 Channel Mixer命令&#xff0c;可以创建高品质的灰度图像、棕褐色图像或其他色调图像&#xff0c;也可以对图像进行创造性的颜色调整&#xff0c;还常用于偏色校正。 要掌握通道混合器的使用方法&#xff0c;需先了解一些基础概念和方法。 1、原色通道 在不同的…

让手机平板成为AI开发利器:AidLux

想ssh登录自己的手机吗&#xff1f; 想在手机上自由的安装lynx、python、vscode、jupyter甚至飞桨PaddlePaddle、Tensorflow、Pytorch和昇思Mindspore吗&#xff1f; 那么看这里....装上AidLux&#xff0c;以上全都有&#xff01; AidLux是一个综合的AI开发平台&#xff0c;…

Vue 与 React:前端框架对比分析

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

Chrome之解决:插件不能使用问题(十三)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 优质专栏&#xff1a;多媒…

深入理解与实践AB测试:从理论到实战案例解析

一、引言 在互联网产品优化和运营策略制定中&#xff0c;AB测试&#xff08;也称为分组测试或随机化对照实验&#xff09;是一种科学且严谨的方法。它通过将用户群体随机分配至不同的实验组&#xff08;通常是A组和B组&#xff09;&#xff0c;对比不同版本的产品或策略对关键…

基于SpringBoot和Vue的校园管理系统的设计与实现

今天要和大家聊的是一款基于SpringBoot和Vue的校园管理系统的设计与实现 &#xff01;&#xff01;&#xff01; 有需要的小伙伴可以通过文章末尾名片咨询我哦&#xff01;&#xff01;&#xff01; &#x1f495;&#x1f495;作者&#xff1a;李同学 &#x1f495;&#x1f…

深入理解Vue的生命周期机制

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

【检索稳定|火爆征稿中】2024年企业管理与数字化经济国际学术会议(ICBMDE 2024)

【检索稳定|火爆征稿中】2024年企业管理与数字化经济国际学术会议&#xff08;ICBMDE 2024&#xff09; 2024 International Conference on Business Management and Digital Economy&#xff08;ICBMDE 2024&#xff09; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~…

【tingsboard开源平台】下载数据库,IDEA编译,项目登录

一&#xff0c; PostgreSQL 下载 需要看官网的&#xff1a;点此下载直达地址&#xff1a;点此进行相关学习&#xff1a;PostgreSQL 菜鸟教程 二&#xff0c;PostgreSQL 安装 点击安装包进行安装 出现乱码错误&#xff1a; There has been an error. Error running C:\Wind…

鸿蒙雄起!风口就在当下,你如何抉择?

近年来&#xff0c;华为自主研发的鸿蒙操作系统&#xff08;HarmonyOS&#xff09;引起了广泛的关注和讨论。鸿蒙系统不仅标志着华为在软件领域的一次重大突破&#xff0c;也预示着全球智能设备市场格局的潜在变化。本文将深入探讨鸿蒙系统的兴起、其在市场上的表现以及对程序员…

【b站李炎恢】Vue.js Element UI | 十天技能课堂 | 更新中... | 李炎恢

课程地址&#xff1a;【Vue.js Element UI | 十天技能课堂 | 更新中... | 李炎恢】 https://www.bilibili.com/video/BV1U54y127GB/?share_sourcecopy_web&vd_sourceb1cb921b73fe3808550eaf2224d1c155 备注&#xff1a;虽然标题声明还在更新中&#xff0c;但是看一些常用…

前端Vue开发技术总结

VUE官网:https://cn.vuejs.org/ VUE官方教程:https://v2.cn.vuejs.org/v2/guide/ Vite官网:https://cn.vitejs.dev/guide/ Element Plus官网:http://element-plus.org/zh-CN/ VsCode常用快捷键 vscode 代码自动对齐快捷键:Shift+Alt+F 一、新建项目 完整的项目结构图如…