R1周

编程入门 行业动态 更新时间:2024-10-13 18:23:44

R1周

R1周

  • 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍦 参考文章地址:🔗深度学习100例-循环神经网络(RNN)心脏病预测 | 第46天
  • 🍖 作者:K同学啊
  • 电脑系统:Windows 10
  • 语言环境:Python 3.8.5
  • 编译器:Pycharm 2022.02
  • 深度学习环境:TensorFlow 2.10.0
  • 显卡及显存:RTX 3060 12G

目录

前言

一、数据集

二、使用步骤

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 tfgpus = tf.config.list_physical_devices("GPU")if gpus:gpu0 = gpus[0]                                        #如果有多个GPU,仅使用第0个GPUtf.config.experimental.set_memory_growth(gpu0, True)  #设置GPU显存用量按需使用tf.config.set_visible_devices([gpu0],"GPU")

2、读入数据

import pandas as pd
import numpy as npdf = 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_splitx = 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,SimpleRNNmodel = 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)
modelpile(loss='binary_crossentropy', optimizer=opt,metrics=['accuracy'])

2、训练函数

epochs = 50history = 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 pltacc = 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实现心脏病预测

更多推荐

R1周

本文发布于:2024-02-07 06:58:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754129.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!