• 【信号处理】基于CNN的心电(ECG)信号分类典型方法实现(tensorflow)


    关于

    本实验使用1维卷积神经网络实现心电信号的5分类。由于数据类别不均衡,这里使用典型的上采样方法,实现数据类别的均衡化处理。

    工具

     

    方法实现

    数据加载

    1. ''' Read the CSV file datasets: NORMAL_LABEL=0 , ABNORMAL_LABEL=1,2,3,4,5 '''
    2. ptbdb_abnormal=pd.read_csv(os.path.join('/input/heartbeat', 'ptbdb_abnormal.csv'),header=None)
    3. ptbdb_normal=pd.read_csv(os.path.join('/input/heartbeat', 'ptbdb_normal.csv'),header=None)
    4. ptbdb_train=pd.concat([ptbdb_abnormal,ptbdb_normal],ignore_index=True)
    5. mitbih_train=pd.read_csv(os.path.join('/input/heartbeat', 'mitbih_train.csv'),header=None)
    6. mitbih_test=pd.read_csv(os.path.join('/input/heartbeat', 'mitbih_test.csv'),header=None)
    7. '''VISUALIZE THE [MITBIH_TRAIN] DATASET: You will observe that majority of the obsvns are of Label=0'''
    8. fig,ax=plt.subplots(figsize=(8,8))
    9. mitbih_train[187].value_counts().plot(ax=ax,kind='bar')
    10. plt.show()
    11. full_train=pd.concat([mitbih_train,ptbdb_train],ignore_index=True)
    12. full_train.shape #102106*188
    13. '''BREAK DOWN THE FULL TRAIN DATASET INTO X & Y'''
    14. full_train_y=full_train[187]
    15. full_train_x=full_train.drop(columns=[187])
    16. '''BREAK DOWN THE TEST DATASET INTO X & Y'''
    17. mitbih_test_y=mitbih_test[187]
    18. mitbih_test_x=mitbih_test.drop(columns=[187])

     信号可视化

    1. plots= [['Normal Beat','Supraventricular Ectopic Beat'], ['Ventricular Ectopic Beat', 'Fusion Ectopic Beat'], ['Unknown']]
    2. colors= [['green', 'orange'], ['red', 'blue'], ['grey']]
    3. fig, axs = plt.subplots(3, 2, constrained_layout=True, figsize=(14,14))
    4. fig.delaxes(axs[2,1])
    5. for i in range(0,5,2):
    6. j=i//2
    7. axs[j][0].plot(mitbih_train[mitbih_train[187]==i%5].sample(1, random_state=100).iloc[0,:186], colors[j][0])
    8. axs[j][0].set_title('{}. {}'.format(i%5,plots[j][0]))
    9. if i%5!=4:
    10. axs[j][1].plot(mitbih_train[mitbih_train[187]==(i%5)+1].sample(1, random_state=100).iloc[0,:186], colors[j][1])
    11. axs[j][1].set_title('{}. {}'.format(i%5+1,plots[j][1]))

     使用上采样方法处理数据不均衡

    1. '''RESAMPLING THE CLASSES TO HAVE EQUAL DATA DISTRIBUTION LED TO WORSEN PERFORMANCE (POSSIBLE UNDERFITTING REASON)'''
    2. df0=mitbih_train[mitbih_train[187]==0].sample(n=20000,random_state=10)
    3. df1=mitbih_train[mitbih_train[187]==1]
    4. df2=mitbih_train[mitbih_train[187]==2]
    5. df3=mitbih_train[mitbih_train[187]==3]
    6. df4=mitbih_train[mitbih_train[187]==4]
    7. df1_upsampled=resample(df1,replace=True,n_samples=20000,random_state=100)
    8. df2_upsampled=resample(df2,replace=True,n_samples=20000,random_state=101)
    9. df3_upsampled=resample(df3,replace=True,n_samples=20000,random_state=102)
    10. df4_upsampled=resample(df4,replace=True,n_samples=20000,random_state=103)
    11. train_df=pd.concat([df1_upsampled,df2_upsampled,df3_upsampled,df4_upsampled,df0])
    12. print(train_df[187].value_counts())
    13. plt.figure(figsize=(10,10))
    14. plt.pie(train_df[187].value_counts(), labels=['N','Q','V','S','F'],
    15. colors=['orange','yellow','lightblue','lightgreen','grey'], autopct='%.2f%%')
    16. plt.gcf().gca().add_artist(plt.Circle( (0,0), 0.7, color='white' ))
    17. plt.title('Balanced classes after upsampling')
    18. plt.show()

    模型搭建

    1. model=tf.keras.Sequential()
    2. model.add(tf.keras.layers.Convolution1D(filters=50,kernel_size=20,activation='relu',kernel_initializer='glorot_uniform',input_shape=(187,1)))
    3. #a1_0=> 187-20+1= 168,50
    4. model.add(tf.keras.layers.MaxPool1D(pool_size=10,data_format='channels_first'))
    5. #a1_1=> 50//10= 168,5
    6. model.add(tf.keras.layers.Convolution1D(filters=20,kernel_size=15,activation='relu',kernel_initializer='glorot_uniform'))
    7. #a2_0=> 168-15+1= 154,20
    8. model.add(tf.keras.layers.MaxPool1D(pool_size=15,data_format='channels_first'))
    9. #a2_1=> 20//15= 154,1
    10. model.add(tf.keras.layers.Convolution1D(filters=10,kernel_size=10,activation='relu',kernel_initializer='glorot_uniform'))
    11. #a3_0=> 154-10+1=145,10
    12. model.add(tf.keras.layers.MaxPool1D(pool_size=10,data_format='channels_first'))
    13. #a3_1=> 10//10=145,1
    14. model.add(tf.keras.layers.Flatten())
    15. #a4=> 145
    16. model.add(tf.keras.layers.Dense(units=512,activation='relu',kernel_initializer='glorot_uniform'))
    17. #a4=> 512
    18. model.add(tf.keras.layers.Dense(units=128,activation='relu',kernel_initializer='glorot_uniform'))
    19. #a5=> 128
    20. model.add(tf.keras.layers.Dense(units=5,activation='softmax'))
    21. model.compile(optimizer='Adam',loss='sparse_categorical_crossentropy',metrics=['acc'])
    22. model.summary()

     模型训练

    1. mitbih_test_x2=np.asarray(mitbih_test_x)
    2. mitbih_test_x2=mitbih_test_x2.reshape(-1,187,1)
    3. ''' DATASET AFTER UPSAMPLING, WITH EVEN DISTRIBUTION ACROSS CLASSES '''
    4. train_df_X=np.asarray(train_df.iloc[:,:187]).reshape(-1,187,1)
    5. train_df_Y=train_df.iloc[:,187]
    6. print(train_df_X.shape)
    7. hist=model.fit(train_df_X,train_df_Y,batch_size=64,epochs=20)

     

    代码获取

    相关项目和问题,后台私信交流沟通。

  • 相关阅读:
    开发知识付费小程序的兴起:机会与挑战
    【UE 材质】模型部分透明
    centos安装docker及oracle
    JDK1.8新特性---Stream API
    Kubernetes(k8s)的流量负载组件Service的ClusterIP类型讲解与使用
    前端实现PDF预览:简单而高效的方法
    YOLOv6、PP-YOLOE、PicoDet选择TOOD
    Linux(基于Centos7)(四)
    iPhone取消Siri语音关机是好是坏
    视频用二维码怎么分享?扫码看视频在线制作方法
  • 原文地址:https://blog.csdn.net/YINTENAXIONGNAIER/article/details/138038943