R3打卡——tensorflow实现RNN心脏病预测

🍨 本文为 🔗365天深度学习训练营中的学习记录博客

1.检查GPU

复制代码
import tensorflow as tf
import pandas     as pd
import numpy      as np

gpus = tf.config.list_physical_devices("GPU")
if gpus:
    tf.config.experimental.set_memory_growth(gpus[0], True)  #设置GPU显存用量按需使用
    tf.config.set_visible_devices([gpus[0]],"GPU")
print(gpus)

2.查看数据

复制代码
import pandas as pd
import numpy as np

df = pd.read_csv("data/heart.csv")
df

# 检查是否有空值
df.isnull().sum()

​

3.划分数据集

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

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

​​​

​​​​​

4.创建模型与编译训练

复制代码
import tensorflow
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,LSTM,SimpleRNN

model = Sequential()
model.add(SimpleRNN(200, input_shape= (13,1), activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.summary()

​​​​5.编译及训练模型

复制代码
opt = tf.keras.optimizers.Adam(learning_rate=1e-4)

model.compile(loss='binary_crossentropy',
              optimizer=opt,
              metrics=["accuracy"])

epochs = 100

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

​​​​​

6.结果可视化

复制代码
import matplotlib.pyplot as plt
from datetime import datetime
current_time = datetime.now() # 获取当前时间

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.xlabel(current_time) # 打卡请带上时间戳,否则代码截图无效

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()

​​​​

​​​​​7.模型评估

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

​​​​​​​​​​​​

总结:

1.RNN

1. RNN是什么?

RNN是一种专门处理序列数据 的神经网络。它的特点是能够利用​"记忆"​​(隐藏状态)来捕捉序列中的时序信息。比如:

  • 自然语言(句子中的单词顺序)
  • 时间序列数据(股票价格、传感器数据)
  • 语音信号(声音的先后顺序)

传统神经网络(如CNN)假设输入是独立的,而RNN通过循环结构让当前时刻的输出依赖之前的输入,从而建模时间依赖关系。


​2. 核心思想:循环与记忆

  • 隐藏状态(Hidden State)​:RNN的"记忆单元",保存了历史信息。
  • 循环机制 :每一步的隐藏状态会传递到下一步,与当前输入共同决定输出。
    公式简化版 :
    ht=f(ht−1,xt)
    其中,ht是当前时刻的隐藏状态,xt是当前输入,f是激活函数(如tanh)
​2. 实验概述

本实验基于心脏病诊断数据构建二分类模型,目标是通过患者生理特征预测心脏病存在与否。采用标准化预处理后的数据输入SimpleRNN网络,结合全连接层进行特征学习与分类。实验通过100轮训练,以Adam优化器(学习率1e-4)和二元交叉熵损失函数优化模型,最终通过准确率评估性能,并可视化训练过程曲线。


3. 核心结果分析
  • ​模型有效性

    模型在训练集与测试集上均展现出稳定的学习趋势。训练后期,训练集与验证集的准确率曲线趋近 ,表明模型未出现显著过拟合;损失曲线同步下降,反映优化过程收敛稳定。测试集准确率(需运行后获取具体数值)可初步验证模型对心脏病预测任务的适用性。

  • ​结构适配性

    尽管SimpleRNN常用于时间序列数据,但本实验将非时序的静态特征重塑为序列格式输入RNN,可能引入冗余计算。若数据无时序关联性,可尝试全连接网络(DNN)​ 或卷积网络(CNN)​简化结构,提升效率。

相关推荐
默|笙1 分钟前
【AI应用】认识机器学习与深度学习
人工智能·深度学习·机器学习
TangGeeA1 分钟前
数据库、SQL 与 DB AI
数据库·人工智能·sql
火山引擎开发者社区2 分钟前
案例实践 | 让检索为 Agent 而生:ContextSearch 重构企业售前知识库
人工智能
青蓝智慧马老师4 分钟前
大模型应用落地,到底靠什么?RAG、智能体和上下文工程一次讲清
人工智能
程序员梅雨5 分钟前
【从零开始学习数据仓库 | 第二篇】: 拉链表 & 数仓分层
大数据·数据仓库·学习
JAVA_AI人工智能项目实战15 分钟前
深度学习实验笔记
人工智能·深度学习·语言模型·自然语言处理
forest_0918 分钟前
当 AI 搜索开始「自我进化」,谁来进化它的核实?——「已核实」结论复核器:3 条结论挖出 2 个洞(附可运行代码)
人工智能·python·机器学习·prompt·agi
金海星科技18 分钟前
船舶交通管理中心的人工智能值守:从“听、说、读、写“看人机协同
人工智能·macos·xcode
释厄62319 分钟前
AI 军备竞赛悖论——为 AI 卖游戏但 AI 需要游戏母场景
人工智能·游戏·kotlin
十铭忘23 分钟前
Orin新系统常用软件安装教程
人工智能