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

相关文章

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

关于数据埋点,你需要了解这些基本知识

产品汪每天都在和数据打交道,你知道数据来自哪里吗? 移动app端内的用户行为数据大多来自埋点,了解一些埋点知识,能和数据分析师、技术侃大山,参与到前期的数据采集,更重要是让最终的埋点数据能为我所用,否则可怜巴巴等上几个月是常有的事。   埋点类型 根据埋点方式,可以区分为: 手动埋点半自动埋点全自动埋点 秉承“任何事物都有两面性”的道理:自动程度高的,能解决通用统计,便于统一化管理,但个性化定

基于人工智能的图像分类系统

目录 引言项目背景环境准备 硬件要求软件安装与配置系统设计 系统架构关键技术代码示例 数据预处理模型训练模型预测应用场景结论 1. 引言 图像分类是计算机视觉中的一个重要任务,目标是自动识别图像中的对象类别。通过卷积神经网络(CNN)等深度学习技术,我们可以构建高效的图像分类系统,广泛应用于自动驾驶、医疗影像诊断、监控分析等领域。本文将介绍如何构建一个基于人工智能的图像分类系统,包括环境

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

异构存储(冷热数据分离)

异构存储主要解决不同的数据,存储在不同类型的硬盘中,达到最佳性能的问题。 异构存储Shell操作 (1)查看当前有哪些存储策略可以用 [lytfly@hadoop102 hadoop-3.1.4]$ hdfs storagepolicies -listPolicies (2)为指定路径(数据存储目录)设置指定的存储策略 hdfs storagepolicies -setStoragePo

Hadoop集群数据均衡之磁盘间数据均衡

生产环境,由于硬盘空间不足,往往需要增加一块硬盘。刚加载的硬盘没有数据时,可以执行磁盘数据均衡命令。(Hadoop3.x新特性) plan后面带的节点的名字必须是已经存在的,并且是需要均衡的节点。 如果节点不存在,会报如下错误: 如果节点只有一个硬盘的话,不会创建均衡计划: (1)生成均衡计划 hdfs diskbalancer -plan hadoop102 (2)执行均衡计划 hd

认识、理解、分类——acm之搜索

普通搜索方法有两种:1、广度优先搜索;2、深度优先搜索; 更多搜索方法: 3、双向广度优先搜索; 4、启发式搜索(包括A*算法等); 搜索通常会用到的知识点:状态压缩(位压缩,利用hash思想压缩)。

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi