Advertisement

基于神经网络rnn模型心脏病特征预测心脏病

阅读量:

预备准备:

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

数据准备:

数据介绍:

复制代码
 数据介绍:

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

    
 import numpy as np
    
  
    
 df = pd.read_csv("heart.csv")
    
 df
    
    
    
    
    代码解读
复制代码
 # 检查是否有空值

    
 df.isnull().sum()
    
    
    
    
    代码解读

数据预处理 :

划分训练集与测试集
🍺 测试集与验证集的关系:

验证集没有参与梯度下降的过程,在狭义上未对模型参数进行训练更新。

但是从更广泛的角度来看,在机器学习中验证集的作用体现在它参与了一个"人工调参"的过程。具体而言,在每个 epoch 训练结束后观察模型在 valid data 上的表现后判断是否有必要实施 early stopping 策略;或者通过该过程观察到的性能变化来调节模型的超参数设置(如学习率、batch_size 等)。

同样可以认为,验证集在训练过程中被纳入了训练阶段,但结果发现该方法并未导致模型在验证集上发生过拟合现象。

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

构建RNN模型:

复制代码
  
    
 tf.keras.layers.SimpleRNN(units,activation='tanh',use_bias=True,kernel_initializer='glorot_uniform',recurrent_initializer='orthogonal',bias_initializer='zeros',kernel_regularizer=None,recurrent_regularizer=None,bias_regularizer=None,activity_regularizer=None,kernel_constraint=None,recurrent_constraint=None,bias_constraint=None,dropout=0.0,recurrent_dropout=0.0,return_sequences=False,return_state=False,go_backwards=False,stateful=False,unroll=False,**kwargs)
    
    
    
    
    代码解读

关键参数说明

● units: 正整数,输出空间的维度。

activation parameter: 所使用的激活函数类型,默认设置为双曲正切函数(tanh)。当参数设置为 None 时,则表示不应用任何激活函数(等同于线性激活,即 a(x) = x)。

● use_bias: 布尔值,该层是否使用偏置向量。

kernel_initializer: weight matrix initializer, 负责对输入进行线性变换 (参考 initializers).

recurrent_init_func: recurrent_kernel 作为权重矩阵 的 初始化函数,在循环单元的状态处理中执行 线性变换。(详见 initializers)。

● bias_initializer:偏置向量的初始化器 (详见initializers).

● dropout: 在 0 和 1 之间的浮点数。 单元的丢弃比例,用于输入的线性转换。

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

编译模型

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

Epoch 97/100
3/3 [==============================] - 0s 25ms/step - loss: 0.2783 - accuracy: 0.8929 - val_loss: 0.3175 - val_accuracy: 0.8710
Epoch 98/100
3/3 [==============================] - 0s 25ms/step - loss: 0.2559 - accuracy: 0.9036 - val_loss: 0.3163 - val_accuracy: 0.8710
Epoch 99/100
3/3 [==============================] - 0s 24ms/step - loss: 0.2658 - accuracy: 0.8863 - val_loss: 0.3143 - val_accuracy: 0.9032
Epoch 100/100
3/3 [==============================] - 0s 24ms/step - loss: 0.2728 - accuracy: 0.8842 - val_loss: 0.3081 - val_accuracy: 0.8710

模型评估:

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

全部评论 (0)

还没有任何评论哟~