R1周-心脏病预测

目录

前言

一、数据集

二、使用步骤

1、默认启动GPU,没有的话则使用CPU

2、读入数据

3、检查数据

三、数据预处理

1、划分数据集

2、数据标准化

四、构建RNN网络

1、函数模型

2、构建函数模型

五、训练模型

1、超参数

2、训练函数

3、测试函数

4、模型评估

总结

参考资料


前言

RNN的原理:


 简单的RNN网络结构包括一个输入层、一个隐藏层和一个输出层,主要用来处理序列任务。

一、数据集

303 rows × 14 columns

其中每个数据的标签含义为:

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 = 心脏病发作的几率更大
 

二、使用步骤

1、默认启动GPU,没有的话则使用CPU

代码如下(示例):

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、读入数据

import pandas as pd
import numpy as np

df = pd.read_csv("E:\DL_data\Day21\heart.csv")
df

3、检查数据

df.isnull().sum()

三、数据预处理

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

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)

四、构建RNN网络

1、函数模型

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
)

2、构建函数模型

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

五、训练模型

1、超参数

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

2、训练函数

epochs = 50

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

3、测试函数

model.evaluate(x_test,y_test)

4、模型评估

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

总结

RNN也有一定的局限性,那就是RNN具有长距离依赖,很难处理长序列的数据,而且由于其模型的特性,它比起神经网络更容易出现梯度消失和梯度爆炸的问题。

参考资料

循环神经网络RNN以及几种经典模型
深度学习 Day21——利用RNN实现心脏病预测

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值