使用Python+TensorFlow2构建基于卷积神经网络(CNN)的ECG心电信号识别分类代码
时间: 2024-05-13 19:15:49 浏览: 169
好的,以下是基于卷积神经网络(CNN)的ECG心电信号识别分类代码的示例:
首先,导入所需的库:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.layers import Input, Conv1D, BatchNormalization, Activation, Flatten, Dense, Dropout
from tensorflow.keras.models import Model
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
```
接下来,加载数据集。在这里,我们将使用MIT-BIH Arrhythmia Database中的ECG信号数据集,该数据集包含大量ECG信号和其对应的心律失常标签。
```python
# 加载数据集
data = pd.read_csv('mitbih_train.csv', header=None)
# 分离特征和标签
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
# 将标签转换为one-hot编码
y = tf.keras.utils.to_categorical(y)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 将特征缩放到标准正态分布
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 将数据转换为3D张量形式
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
```
接下来是模型的构建部分。我们使用一维卷积层和批量归一化层来提取特征,然后使用全连接层和Dropout层进行分类。
```python
# 定义模型结构
inputs = Input(shape=(X_train.shape[1], 1))
x = Conv1D(filters=32, kernel_size=5, strides=1, padding='same')(inputs)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv1D(filters=64, kernel_size=5, strides=1, padding='same')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Conv1D(filters=128, kernel_size=5, strides=1, padding='same')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Flatten()(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(5, activation='softmax')(x)
# 定义模型
model = Model(inputs=inputs, outputs=x)
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 打印模型摘要
model.summary()
```
最后,我们训练模型并进行评估。
```python
# 训练模型
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=128)
# 评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# 绘制训练和验证集上的准确率曲线
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()
```
这就是基于卷积神经网络(CNN)的ECG心电信号识别分类代码的示例。
阅读全文