tensorflow-实现RNN预测心脏病

 

我的环境

  • 难度:新手入门⭐

🍺要求:

  1. 本地读取并加载数据。(✔)
  2. 了解循环神经网络(RNN)的构建过程(✔)
  3. 测试集accuracy到达87%(✔)

🍻拔高:

  1. 测试集accuracy到达89%(✔)

目录

一 前期工作

1.设置GPU或者cpu

2.导入数据

二 数据预处理

三 搭建网络

四 训练模型

1.设置参数

 2.开始训练

​编辑

五 模型评估

1.Loss和Accuracy图

 2.对结果进行预测

3.总结 


一 前期工作

环境:python3.6,1080ti,tensorflow2.5(实验室服务器的环境😂😂)

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

2.导入数据

import pandas as pd
import numpy as np

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

二 数据预处理

数据格式设置

# 检查是否有空值
df.isnull().sum()

数据集划分

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)

三 搭建网络

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

打印网络结构

四 训练模型

1.设置参数

opt = tf.keras.optimizers.Adam(learning_rate=1e-2)

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

 2.开始训练

epochs = 100

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

五 模型评估

1.Loss和Accuracy图

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

 2.对结果进行预测

scores = model.evaluate(X_test, y_test, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

3.总结 

1.修改学习率为0.01,准确率得到提高,最高为:93%

2.RNN的参数如下

3.我发现我还是适合做pytorch的,因为论文也是这方面,所以这次就当水一下了 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值