【深度学习练习】心脏病预测

一、什么是RNN

RNN与传统神经网络最大的区别在于,每次都会将前一次的输出结果,带到下一隐藏层中一起训练。如下图所示:
在这里插入图片描述

二、前期工作

1. 设置GPU

import tensorflow as tf

gpus = tf.config.list_physical_devices("GPU")

if gpus:
    gpu0 = gpus[0]                                        #如果有多个GPU,仅使用第0个GPU
    tf.config.experimental.set_memory_growth(gpu0, True)  #设置GPU显存用量按需使用
    tf.config.set_visible_devices([gpu0],"GPU")

2. 导入数据

数据介绍:

age:年龄
sex:性别
cp:胸痛类型 (4 values)
trestbps:静息血压
chol:血清胆甾醇 (mg/dl)
fbs:空腹血糖 > 120 mg/dl
restecg:静息心电图结果 (值 0,1 ,2)
thalach:达到的最大心率
exang:运动诱发的心绞痛
oldpeak:相对于静止状态,运动引起的ST段压低
slope:运动峰值 ST 段的斜率
ca:荧光透视着色的主要血管数量 (0-3)
thal:0 = 正常;1 = 固定缺陷;2 = 可逆转的缺陷
target:0 = 心脏病发作的几率较小 1 = 心脏病发作的几率更大

import pandas as pd
import numpy as np

df = pd.read_csv(r"D:\Personal Data\Learning Data\DL Learning Data\heart.csv")
df

输出:
在这里插入图片描述

3. 检查数据

df.isnull().sum()

输出:
在这里插入图片描述

三、数据预处理

1. 划分数据集

from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

x = df.iloc[:,:-1]
y = df.iloc[:,-1]

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state=1)

x_train.shape, y_train.shape

输出:
在这里插入图片描述

2. 标准化

# 将每一列特征标准化为标准正太分布,注意,标准化是针对每一列而言的
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test  = sc.transform(x_test)

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)

3. 构建RNN模型

import tensorflow
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,LSTM,SimpleRNN

model = Sequential()
model.add(SimpleRNN(128, input_shape= (13,1),return_sequences=True,activation='relu'))
model.add(SimpleRNN(64,return_sequences=True, activation='relu'))
model.add(SimpleRNN(32, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.summary()

输出:
在这里插入图片描述

五、编译模型

opt = tf.keras.optimizers.Adam(learning_rate=1e-4)
model.compile(loss='binary_crossentropy', optimizer=opt,metrics=['accuracy'])

六、训练模型

epochs = 50

history = model.fit(x_train, y_train,
                    epochs=epochs,
                    batch_size=128,
                    validation_data=(x_test, y_test),
                    verbose=1)

部分输出:
在这里插入图片描述

model.evaluate(x_test,y_test)

输出:
在这里插入图片描述

七、模型评估

import matplotlib.pyplot as plt

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

epochs_range = range(epochs)

plt.figure(figsize=(14, 4))
plt.subplot(1, 2, 1)

plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

最后准确率输出:

scores = model.evaluate(x_test, y_test, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

八、总结

  1. 注意numpy与panda以及matplotlib等之间的兼容性
  2. 注意对每一列的特征数据标准化处理
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!对于心脏病预测的问题,使用循环神经网络(RNN)是一种常见的方法。RNN适用于处理序列数据,而心电图信号就是一种序列数据。在使用RNN进行心脏病预测时,你可以将心电图信号作为输入序列,然后通过训练RNN模型来预测患者是否患有心脏病。 首先,你需要准备一个合适的数据集,其中包含心电图信号和相应的心脏病标签。可以使用公开的心电图数据集,如PTB数据库或MIT-BIH数据库。然后,你可以对数据进行预处理和特征工程,如数据清洗、滤波、降采样等。 接下来,你可以构建一个RNN模型。RNN模型由一系列循环层组成,每个循环层都会处理一个时间步的输入数据。你可以选择不同类型的RNN单元,如简单循环单元(SimpleRNN)、长短期记忆网络(LSTM)或门控循环单元(GRU)。通过添加适当的全连接层和激活函数,你可以将RNN模型输出映射到二分类问题(有或无心脏病)的结果。 然后,你可以使用训练集对RNN模型进行训练,并使用验证集进行模型调优。在训练过程中,你可以使用适当的损失函数(如交叉熵)和优化算法(如随机梯度下降)来最小化模型的预测误差。 最后,你可以使用测试集对训练好的模型进行评估,并计算模型的性能指标,如准确率、精确率、召回率等。这些指标可以帮助你评估模型的预测能力和泛化能力。 需要注意的是,心脏病预测是一个复杂的医学问题,仅仅使用心电图信号可能不能得到准确的预测结果。通常情况下,还需要结合其他患者的临床信息和医学知识来进行综合评估。因此,在进行心脏病预测时,建议与专业医生合作,并遵循相关的医学准则和规范。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值