mirror of
https://github.com/This-weiyuqing/ECG_by_Diffenert_CNN_Test.git
synced 2026-10-17 19:05:30 +08:00
Initial commit
This commit is contained in:
commit
fcbea99d01
10 files changed
+376
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
+152
@@ -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/
|
||||
Generated
+8
@@ -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
|
||||
Generated
+11
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="jdk" jdkName="ECG_by_Diffenert_CNN_Test" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<component name="PyDocumentationSettings">
|
||||
<option name="renderExternalDocumentation" value="true" />
|
||||
</component>
|
||||
</module>
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
Generated
+4
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="ECG_by_Diffenert_CNN_Test" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
Generated
+8
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/ECG_by_Diffenert_CNN_Test.iml" filepath="$PROJECT_DIR$/.idea/ECG_by_Diffenert_CNN_Test.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="PySciProjectComponent">
|
||||
<option name="PY_SCI_VIEW" value="true" />
|
||||
<option name="PY_SCI_VIEW_SUGGESTED" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user