Advertisement

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

阅读量:

一、什么是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")
    
    
    
    python

2. 导入数据

数据介绍:

age: 年龄
sex: 性别
cp: 胸痛类型(共4个值)
trestbps: 静息血压(mmHg测量值)
chol: 血清胆固醇水平(mg/dl单位)
fbs: 空腹血糖超过120 mg/dl的情况
restecg: 静息心电图结果(数值为0,1,2)
thalach: 最大心率(达到的最大速率)
exang: 运动诱发的心绞痛情况
oldpeak: 相对于静止状态时运动所引起的ST段压低幅度(单位:mm)
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
    
    
    python

输出:

在这里插入图片描述

3. 检查数据

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

输出:

在这里插入图片描述

三、数据预处理

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

输出:

在这里插入图片描述

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

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()
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-16/6z4L28YoyWtcBgjhQGF15R3qlJUP.png)

输出:

在这里插入图片描述

五、编译模型

复制代码
    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
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-16/2WckReIG1jvVdFstl7A8MyJgEhHx.png)

最后准确率输出:

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

八、总结

  1. 确保numpy与panda以及matplotlib等工具之间的一致性和兼容性
  2. 特别关注对每一列特征数据的标准化执行

全部评论 (0)

还没有任何评论哟~