第R3周:RNN-心脏病预测(Tensorflow实现)

  • 语言环境:Python3.8
  • 编译器:Jupyter Lab
  • 深度学习环境:
    • tensorflow==2.18.0+cuda

目录

[1. 前期准备](#1. 前期准备)

1.1设置GPU

[1.2 导入数据](#1.2 导入数据)

[1.3 检查数据](#1.3 检查数据)

[2. 数据预处理](#2. 数据预处理)

[2.1 划分训练集与测试集](#2.1 划分训练集与测试集)

[2.2 标准化](#2.2 标准化)

[3. 构建RNN模型](#3. 构建RNN模型)

[4. 编译模型](#4. 编译模型)

[5. 训练模型](#5. 训练模型)

[​6. 评估模型](#6. 评估模型)


1. 前期准备

1.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")
    
gpus

1.2 导入数据

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

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

1.3 检查数据

python 复制代码
# 检查是否有空值
df.isnull().sum()

2. 数据预处理

2.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)
X_train.shape,y_train.shape

2.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(200,input_shape=(13,1),activation='relu'))
model.add(Dense(100,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.summary()

4. 编译模型

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

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

5. 训练模型

python 复制代码
epochs = 100

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

6. 评估模型

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=(12, 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))

总结:

从上图结果中我们可以看出:

左图:训练与验证准确率

训练集的准确率(蓝色线):随着训练次数增加,呈现出平稳上升趋势,最终接近0.92左右,说明模型在训练数据上的拟合效果逐渐变好。

验证集的准确率(橙色线):一开始随着训练迭代次数增加,验证准确率也在提升,但在约25次迭代后,准确率趋于平稳,甚至有一些波动,特别在60次之后,表现出明显的下降和上升不稳定现象。

右图:训练与验证损失

训练集损失(蓝色线):损失随着迭代次数逐渐下降,这表明模型在训练集上不断优化,误差减少。

验证集损失(橙色线):最开始也在下降,但在大约20次迭代后开始变得平缓,甚至损失值开始回弹。这与验证集准确率下降的现象一致,暗示模型在验证集上的表现没有持续改进。

相关推荐
静心问道6 分钟前
SEW:无监督预训练在语音识别中的性能-效率权衡
人工智能·语音识别
xwz小王子12 分钟前
从LLM到WM:大语言模型如何进化成具身世界模型?
人工智能·语言模型·自然语言处理
我爱一条柴ya13 分钟前
【AI大模型】深入理解 Transformer 架构:自然语言处理的革命引擎
人工智能·ai·ai作画·ai编程·ai写作
静心问道14 分钟前
FLAN-T5:规模化指令微调的语言模型
人工智能·语言模型·自然语言处理
李师兄说大模型14 分钟前
KDD 2025 | 地理定位中的群体智能:一个多智能体大型视觉语言模型协同框架
人工智能·深度学习·机器学习·语言模型·自然语言处理·大模型·deepseek
静心问道15 分钟前
SqueezeBERT:计算机视觉能为自然语言处理在高效神经网络方面带来哪些启示?
人工智能·计算机视觉·自然语言处理
Sherlock Ma15 分钟前
百度开源文心一言4.5:论文解读和使用入门
人工智能·百度·自然语言处理·开源·大模型·文心一言·多模态
weisian15120 分钟前
人工智能-基础篇-18-什么是RAG(检索增强生成:知识库+向量化技术+大语言模型LLM整合的技术框架)
人工智能·语言模型·自然语言处理
DataCastle25 分钟前
第三届Bio-OS AI开源大赛启动会隆重举行
人工智能
后端小肥肠34 分钟前
躺赚必备!RPA+Coze+豆包:公众号自动发文,AI率0%亲测有效(附AI率0%提示词)
人工智能·aigc·coze