commit fcbea99d0187033c128764301d91689dc14b87cd
Author: 魏遇卿 <358614401@qq.com>
Date: Tue Mar 7 21:18:12 2023 +0800
Initial commit
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..dfe0770
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# Auto detect text files and perform LF normalization
+* text=auto
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d9005f2
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,152 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# poetry
+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+#poetry.lock
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+# and can be added to the global gitignore or merged into this file. For a more nuclear
+# option (not recommended) you can uncomment the following to ignore the entire idea folder.
+#.idea/
diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..13566b8
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml
diff --git a/.idea/ECG_by_Diffenert_CNN_Test.iml b/.idea/ECG_by_Diffenert_CNN_Test.iml
new file mode 100644
index 0000000..dc26ab5
--- /dev/null
+++ b/.idea/ECG_by_Diffenert_CNN_Test.iml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 0000000..105ce2d
--- /dev/null
+++ b/.idea/inspectionProfiles/profiles_settings.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..f8d7d56
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..3443cb7
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/other.xml b/.idea/other.xml
new file mode 100644
index 0000000..640fd80
--- /dev/null
+++ b/.idea/other.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/main.py b/main.py
new file mode 100644
index 0000000..d0294e6
--- /dev/null
+++ b/main.py
@@ -0,0 +1,159 @@
+import wfdb
+import pywt
+import seaborn
+# import torch
+import numpy as np
+import matplotlib;matplotlib.use('TkAgg')
+import tensorflow as tf
+import matplotlib.pyplot as plt
+from sklearn.metrics import confusion_matrix
+
+# 测试集在数据集中所占的比例
+RATIO = 0.2
+
+
+# 小波去噪预处理
+def denoise(data):
+ # 小波变换
+ coeffs = pywt.wavedec(data=data, wavelet='db5', level=9)
+ cA9, cD9, cD8, cD7, cD6, cD5, cD4, cD3, cD2, cD1 = coeffs
+ # 阈值去噪
+ threshold = (np.median(np.abs(cD1)) / 0.6745) * (np.sqrt(2 * np.log(len(cD1))))
+ cD1.fill(0)
+ cD2.fill(0)
+ for i in range(1, len(coeffs) - 2):
+ coeffs[i] = pywt.threshold(coeffs[i], threshold)
+ # 小波反变换,获取去噪后的信号
+ rdata = pywt.waverec(coeffs=coeffs, wavelet='db5')
+ return rdata
+
+
+# 读取心电数据和对应标签,并对数据进行小波去噪
+def getDataSet(number, X_data, Y_data):
+ ecgClassSet = ['N', 'A', 'V', 'L', 'R']
+ # 读取心电数据记录
+ print("正在读取 " + number + " 号心电数据...")
+ # 读取MLII导联的数据
+ record = wfdb.rdrecord('W:/MIT-BIT/mit-bih-arrhythmia-database-1.0.0/' + number, channel_names=['MLII'])
+ data = record.p_signal.flatten()
+ rdata = denoise(data=data)
+ # 获取心电数据记录中R波的位置和对应的标签
+ annotation = wfdb.rdann('W:/MIT-BIT/mit-bih-arrhythmia-database-1.0.0/' + number, 'atr')
+ Rlocation = annotation.sample
+ Rclass = annotation.symbol
+ # 去掉前后的不稳定数据
+ start = 10
+ end = 5
+ i = start
+ j = len(annotation.symbol) - end
+ # 因为只选择NAVLR五种心电类型,所以要选出该条记录中所需要的那些带有特定标签的数据,舍弃其余标签的点
+ # X_data在R波前后截取长度为300的数据点
+ # Y_data将NAVLR按顺序转换为01234
+ while i < j:
+ try:
+ # Rclass[i] 是标签
+ lable = ecgClassSet.index(Rclass[i])
+ # 基于经验值,基于R峰向前取100个点,向后取200个点
+ x_train = rdata[Rlocation[i] - 100:Rlocation[i] + 200]
+ X_data.append(x_train)
+ Y_data.append(lable)
+ i += 1
+ except ValueError:
+ i += 1
+ return
+
+
+# 加载数据集并进行预处理
+def loadData():
+ numberSet = ['100', '101', '103', '105', '106', '107', '108', '109', '111', '112', '113', '114', '115',
+ '116', '117', '119', '121', '122', '123', '124', '200', '201', '202', '203', '205', '208',
+ '210', '212', '213', '214', '215', '217', '219', '220', '221', '222', '223', '228', '230',
+ '231', '232', '233', '234']
+ dataSet = []
+ lableSet = []
+ for n in numberSet:
+ getDataSet(n, dataSet, lableSet)
+ # 转numpy数组,打乱顺序
+ dataSet = np.array(dataSet).reshape(-1, 300)
+ lableSet = np.array(lableSet).reshape(-1, 1)
+ train_ds = np.hstack((dataSet, lableSet))
+ np.random.shuffle(train_ds)
+ # 数据集及其标签集
+ X = train_ds[:, :300].reshape(-1, 300, 1)
+ Y = train_ds[:, 300]
+ # 测试集及其标签集
+ shuffle_index = np.random.permutation(len(X))
+ # 设定测试集的大小 RATIO是测试集在数据集中所占的比例
+ test_length = int(RATIO * len(shuffle_index))
+ # 测试集的长度
+ test_index = shuffle_index[:test_length]
+ # 训练集的长度
+ train_index = shuffle_index[test_length:]
+ X_test, Y_test = X[test_index], Y[test_index]
+ X_train, Y_train = X[train_index], Y[train_index]
+ return X_train, Y_train, X_test, Y_test
+
+
+# 构建CNN模型
+def buildModel():
+ newModel = tf.keras.models.Sequential([
+ tf.keras.layers.InputLayer(input_shape=(300, 1)),
+ # 第一个卷积层, 4 个 21x1 卷积核
+ tf.keras.layers.Conv1D(filters=4, kernel_size=21, strides=1, padding='SAME', activation='tanh'),
+ # 第一个池化层, 最大池化,4 个 3x1 卷积核, 步长为 2
+ tf.keras.layers.MaxPool1D(pool_size=3, strides=2, padding='SAME'),
+ # 第二个卷积层, 16 个 23x1 卷积核
+ tf.keras.layers.Conv1D(filters=16, kernel_size=23, strides=1, padding='SAME', activation='relu'),
+ # 第二个池化层, 最大池化,4 个 3x1 卷积核, 步长为 2
+ tf.keras.layers.MaxPool1D(pool_size=3, strides=2, padding='SAME'),
+ # 第三个卷积层, 32 个 25x1 卷积核
+ tf.keras.layers.Conv1D(filters=32, kernel_size=25, strides=1, padding='SAME', activation='tanh'),
+ # 第三个池化层, 平均池化,4 个 3x1 卷积核, 步长为 2
+ tf.keras.layers.AvgPool1D(pool_size=3, strides=2, padding='SAME'),
+ # 第四个卷积层, 64 个 27x1 卷积核
+ tf.keras.layers.Conv1D(filters=64, kernel_size=27, strides=1, padding='SAME', activation='relu'),
+ # 打平层,方便全连接层处理'
+ tf.keras.layers.Flatten(),
+ # 全连接层,128 个节点 转换成128个节点
+ tf.keras.layers.Dense(128, activation='relu'),
+ # Dropout层,dropout = 0.2
+ tf.keras.layers.Dropout(rate=0.2),
+ # 全连接层,5 个节点
+ tf.keras.layers.Dense(5, activation='softmax')
+ ])
+ return newModel
+
+
+def plotHeatMap(Y_test, Y_pred):
+ con_mat = confusion_matrix(Y_test, Y_pred)
+ # 绘图
+ fig=plt.figure(figsize=(4, 5))
+ seaborn.heatmap(con_mat, annot=True, fmt='.20g', cmap='Blues')
+ plt.ylim(0, 5)
+ plt.xlabel('Predicted labels')
+ plt.ylabel('True labels')
+ plt.show(fig)
+
+
+def main():
+ # X_train,Y_train为所有的数据集和标签集
+ # X_test,Y_test为拆分的测试集和标签集
+ X_train, Y_train, X_test, Y_test = loadData()
+ print(X_train.shape)
+
+ model = buildModel()
+ model.compile(optimizer='adam',
+ loss='sparse_categorical_crossentropy', metrics=['accuracy']
+ # metrics: 列表,包含评估模型在训练和测试时的性能的指标,典型用法是metrics=[‘accuracy’]。
+ )
+ model.summary()
+
+ # 训练与验证
+ model.fit(X_train, Y_train, epochs=30, batch_size=128, validation_split=RATIO) # validation_split 训练集所占比例
+ # 预测
+ Y_pred = model.predict(X_test)
+ print(Y_pred)
+ plotHeatMap(Y_test,Y_pred)
+
+if __name__ == '__main__':
+ main()
diff --git a/testpltshow.py b/testpltshow.py
new file mode 100644
index 0000000..c544fea
--- /dev/null
+++ b/testpltshow.py
@@ -0,0 +1,19 @@
+## read_img.py
+
+import cv2
+import os
+import matplotlib.pyplot as plt
+from PIL import Image
+
+source_path='E:/CToE/Pictures'
+
+def show_pic():
+ # img=cv2.imread(os.path.join(source_path,'t1.png'))
+ img=Image.open(os.path.join(source_path,'1.png'))
+ # plt.imshow(img)
+ info = plt.imshow(img)
+ print(info)
+ plt.show()
+
+if __name__ == '__main__':
+ show_pic()
\ No newline at end of file