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

一、什么是RNN

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

二、前期工作

1. 设置GPU

python 复制代码
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 = 心脏病发作的几率更大

python 复制代码
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. 检查数据

python 复制代码
df.isnull().sum()

输出:

三、数据预处理

1. 划分数据集

python 复制代码
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)
python 复制代码
x_train.shape, y_train.shape

输出:

2. 标准化

python 复制代码
# 将每一列特征标准化为标准正太分布,注意,标准化是针对每一列而言的
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模型

python 复制代码
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()

输出:

五、编译模型

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

六、训练模型

python 复制代码
epochs = 50

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

部分输出:

python 复制代码
model.evaluate(x_test,y_test)

输出:

七、模型评估

python 复制代码
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()

最后准确率输出:

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

八、总结

  1. 注意numpy与panda以及matplotlib等之间的兼容性
  2. 注意对每一列的特征数据标准化处理
相关推荐
董厂长7 分钟前
langchain :记忆组件混淆概念澄清 & 创建Conversational ReAct后显示指定 记忆组件
人工智能·深度学习·langchain·llm
G皮T3 小时前
【人工智能】ChatGPT、DeepSeek-R1、DeepSeek-V3 辨析
人工智能·chatgpt·llm·大语言模型·deepseek·deepseek-v3·deepseek-r1
九年义务漏网鲨鱼4 小时前
【大模型学习 | MINIGPT-4原理】
人工智能·深度学习·学习·语言模型·多模态
元宇宙时间4 小时前
Playfun即将开启大型Web3线上活动,打造沉浸式GameFi体验生态
人工智能·去中心化·区块链
开发者工具分享4 小时前
文本音频违规识别工具排行榜(12选)
人工智能·音视频
产品经理独孤虾4 小时前
人工智能大模型如何助力电商产品经理打造高效的商品工业属性画像
人工智能·机器学习·ai·大模型·产品经理·商品画像·商品工业属性
老任与码4 小时前
Spring AI Alibaba(1)——基本使用
java·人工智能·后端·springaialibaba
蹦蹦跳跳真可爱5895 小时前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
雷羿 LexChien5 小时前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt
两棵雪松5 小时前
如何通过向量化技术比较两段文本是否相似?
人工智能