深度学习笔记27_RNN实现阿尔茨海默病诊断(pytorch)

server/2024/12/25 0:24:50/
  •   🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍖 原作者:K同学啊 | 接辅导、项目定制

一、我的环境

1.语言环境:Python 3.9

2.编译器:Pycharm

3.深度学习环境:pyTorch 2.1.2

二、GPU设置

       若使用的是cpu则可忽略

import torch# 设置硬件设备,如果有GPU则使用,没有则使用cpu
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

、数据导入

import warningsimport matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import torch.nn as nndf = pd.read_csv("data/data.csv")
df = df.iloc[:, 1:-1]
print(df)
      Age  Gender  ...  Forgetfulness  Diagnosis
0      73       0  ...              0          0
1      89       0  ...              1          0
2      73       0  ...              0          0
3      74       1  ...              0          0
4      89       0  ...              0          0
...   ...     ...  ...            ...        ...
2144   61       0  ...              0          1
2145   75       0  ...              0          1
2146   77       0  ...              0          1
2147   78       1  ...              1          1
2148   72       0  ...              1          0[2149 rows x 33 columns]

、构建数据集

1.标准化 

from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_splitX = df.iloc[:, :-1]
y = df.iloc[:, -1]
# 将每一列特征标准化为标准正太分布,注意,标准化是针对每一列而言的
sc = StandardScaler()
X = sc.fit_transform(X)

2.划分数据集 

X = torch.tensor(np.array(X), dtype=torch.float32)
y = torch.tensor(np.array(y), dtype=torch.int64)
X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.1,random_state=1)
print(X_train.shape, y_train.shape)
#torch.Size([1934, 32]) torch.Size([1934])

3.构建数据加载器 

from torch.utils.data import TensorDataset, DataLoadertrain_dl = DataLoader(TensorDataset(X_train, y_train),batch_size=64,shuffle=False)
test_dl = DataLoader(TensorDataset(X_test, y_test),batch_size=64,shuffle=False)

五、构建模型

class model_rnn(nn.Module):def __init__(self):super(model_rnn, self).__init__()self.rnn0 = nn.RNN(input_size=32, hidden_size=200,num_layers=1, batch_first=True)self.fc0 = nn.Linear(200, 50)self.fc1 = nn.Linear(50, 2)def forward(self, x):out, hidden1 = self.rnn0(x)out = self.fc0(out)out = self.fc1(out)return outmodel = model_rnn().to(device)
print(model)
model_rnn((rnn0): RNN(32, 200, batch_first=True)(fc0): Linear(in_features=200, out_features=50, bias=True)(fc1): Linear(in_features=50, out_features=2, bias=True)
)

六、训练函数

# 训练循环
def train(dataloader, model, loss_fn, optimizer):size = len(dataloader.dataset)  # 训练集的大小num_batches = len(dataloader)  # 批次数目, (size/batch_size,向上取整)train_loss, train_acc = 0, 0  # 初始化训练损失和正确率for X, y in dataloader:  # 获取图片及其标签X, y = X.to(device), y.to(device)# 计算预测误差pred = model(X)  # 网络输出loss = loss_fn(pred, y)  # 计算网络输出和真实值之间的差距,targets为真实值# 反向传播optimizer.zero_grad()  # grad属性归零loss.backward()  # 反向传播optimizer.step()  # 每一步自动更新# 记录acc与losstrain_acc += (pred.argmax(1) == y).type(torch.float).sum().item()train_loss += loss.item()train_acc /= sizetrain_loss /= num_batchesreturn train_acc, train_loss

七、测试函数

def test(dataloader, model, loss_fn):size = len(dataloader.dataset)  # 测试集的大小num_batches = len(dataloader)  # 批次数目, (size/batch_size,向上取整)test_loss, test_acc = 0, 0# 当不进行训练时,停止梯度更新,节省计算内存消耗with torch.no_grad():for imgs, target in dataloader:imgs, target = imgs.to(device), target.to(device)# 计算losstarget_pred = model(imgs)loss = loss_fn(target_pred, target)test_loss += loss.item()test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()test_acc /= sizetest_loss /= num_batchesreturn test_acc, test_loss

八、训练模型

loss_fn = nn.CrossEntropyLoss()  # 创建损失函数
learn_rate = 5e-5  # 学习率
opt = torch.optim.Adam(model.parameters(), lr=learn_rate)
epochs = 50
train_loss = []
train_acc = []
test_loss = []
test_acc = []
for epoch in range(epochs):model.train()epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)model.eval()epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)train_acc.append(epoch_train_acc)train_loss.append(epoch_train_loss)test_acc.append(epoch_test_acc)test_loss.append(epoch_test_loss)# 获取当前的学习率lr = opt.state_dict()['param_groups'][0]['lr']template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f},Lr:{:.2E}')print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss, epoch_test_acc * 100, epoch_test_loss, lr))print("=" * 20, 'Done', "=" * 20)

运行结果: 

Epoch: 1, Train_acc:52.7%, Train_loss:0.691, Test_acc:63.7%, Test_loss:0.673,Lr:5.00E-05
==================== Done ====================
Epoch: 2, Train_acc:68.3%, Train_loss:0.661, Test_acc:71.2%, Test_loss:0.643,Lr:5.00E-05
==================== Done ====================
Epoch: 3, Train_acc:70.7%, Train_loss:0.630, Test_acc:66.5%, Test_loss:0.611,Lr:5.00E-05
==================== Done ====================
Epoch: 4, Train_acc:67.6%, Train_loss:0.600, Test_acc:66.5%, Test_loss:0.588,Lr:5.00E-05
==================== Done ====================
Epoch: 5, Train_acc:67.2%, Train_loss:0.580, Test_acc:66.5%, Test_loss:0.573,Lr:5.00E-05
==================== Done ====================
Epoch: 6, Train_acc:69.4%, Train_loss:0.562, Test_acc:67.9%, Test_loss:0.559,Lr:5.00E-05
==================== Done ====================
Epoch: 7, Train_acc:71.9%, Train_loss:0.543, Test_acc:71.2%, Test_loss:0.544,Lr:5.00E-05
==================== Done ====================
Epoch: 8, Train_acc:74.1%, Train_loss:0.523, Test_acc:72.6%, Test_loss:0.529,Lr:5.00E-05
==================== Done ====================
Epoch: 9, Train_acc:76.1%, Train_loss:0.503, Test_acc:74.9%, Test_loss:0.514,Lr:5.00E-05
==================== Done ====================
Epoch:10, Train_acc:77.8%, Train_loss:0.484, Test_acc:76.7%, Test_loss:0.499,Lr:5.00E-05
==================== Done ====================
Epoch:11, Train_acc:79.9%, Train_loss:0.465, Test_acc:77.7%, Test_loss:0.485,Lr:5.00E-05
==================== Done ====================
Epoch:12, Train_acc:81.1%, Train_loss:0.447, Test_acc:77.7%, Test_loss:0.472,Lr:5.00E-05
==================== Done ====================
Epoch:13, Train_acc:82.5%, Train_loss:0.431, Test_acc:78.1%, Test_loss:0.460,Lr:5.00E-05
==================== Done ====================
Epoch:14, Train_acc:83.3%, Train_loss:0.417, Test_acc:79.1%, Test_loss:0.449,Lr:5.00E-05
==================== Done ====================
Epoch:15, Train_acc:84.3%, Train_loss:0.404, Test_acc:79.1%, Test_loss:0.439,Lr:5.00E-05
==================== Done ====================
Epoch:16, Train_acc:84.6%, Train_loss:0.393, Test_acc:79.5%, Test_loss:0.431,Lr:5.00E-05
==================== Done ====================
Epoch:17, Train_acc:85.1%, Train_loss:0.383, Test_acc:79.5%, Test_loss:0.424,Lr:5.00E-05
==================== Done ====================
Epoch:18, Train_acc:85.1%, Train_loss:0.374, Test_acc:79.5%, Test_loss:0.418,Lr:5.00E-05
==================== Done ====================
Epoch:19, Train_acc:85.5%, Train_loss:0.366, Test_acc:79.1%, Test_loss:0.413,Lr:5.00E-05
==================== Done ====================
Epoch:20, Train_acc:85.7%, Train_loss:0.360, Test_acc:79.1%, Test_loss:0.409,Lr:5.00E-05
==================== Done ====================
Epoch:21, Train_acc:85.8%, Train_loss:0.354, Test_acc:78.6%, Test_loss:0.407,Lr:5.00E-05
==================== Done ====================
Epoch:22, Train_acc:86.1%, Train_loss:0.349, Test_acc:78.6%, Test_loss:0.404,Lr:5.00E-05
==================== Done ====================
Epoch:23, Train_acc:86.2%, Train_loss:0.344, Test_acc:78.1%, Test_loss:0.403,Lr:5.00E-05
==================== Done ====================
Epoch:24, Train_acc:86.6%, Train_loss:0.340, Test_acc:77.2%, Test_loss:0.402,Lr:5.00E-05
==================== Done ====================
Epoch:25, Train_acc:86.6%, Train_loss:0.337, Test_acc:77.2%, Test_loss:0.402,Lr:5.00E-05
==================== Done ====================
Epoch:26, Train_acc:86.6%, Train_loss:0.334, Test_acc:77.2%, Test_loss:0.402,Lr:5.00E-05
==================== Done ====================
Epoch:27, Train_acc:86.7%, Train_loss:0.331, Test_acc:77.2%, Test_loss:0.403,Lr:5.00E-05
==================== Done ====================
Epoch:28, Train_acc:86.8%, Train_loss:0.328, Test_acc:77.7%, Test_loss:0.404,Lr:5.00E-05
==================== Done ====================
Epoch:29, Train_acc:86.9%, Train_loss:0.325, Test_acc:77.7%, Test_loss:0.406,Lr:5.00E-05
==================== Done ====================
Epoch:30, Train_acc:86.9%, Train_loss:0.323, Test_acc:77.7%, Test_loss:0.407,Lr:5.00E-05
==================== Done ====================
Epoch:31, Train_acc:87.0%, Train_loss:0.321, Test_acc:77.7%, Test_loss:0.409,Lr:5.00E-05
==================== Done ====================
Epoch:32, Train_acc:87.2%, Train_loss:0.319, Test_acc:77.2%, Test_loss:0.411,Lr:5.00E-05
==================== Done ====================
Epoch:33, Train_acc:87.3%, Train_loss:0.317, Test_acc:78.1%, Test_loss:0.413,Lr:5.00E-05
==================== Done ====================
Epoch:34, Train_acc:87.3%, Train_loss:0.315, Test_acc:78.6%, Test_loss:0.416,Lr:5.00E-05
==================== Done ====================
Epoch:35, Train_acc:87.4%, Train_loss:0.313, Test_acc:79.1%, Test_loss:0.418,Lr:5.00E-05
==================== Done ====================
Epoch:36, Train_acc:87.7%, Train_loss:0.311, Test_acc:79.1%, Test_loss:0.420,Lr:5.00E-05
==================== Done ====================
Epoch:37, Train_acc:87.9%, Train_loss:0.310, Test_acc:79.5%, Test_loss:0.423,Lr:5.00E-05
==================== Done ====================
Epoch:38, Train_acc:87.9%, Train_loss:0.308, Test_acc:79.5%, Test_loss:0.425,Lr:5.00E-05
==================== Done ====================
Epoch:39, Train_acc:88.0%, Train_loss:0.306, Test_acc:79.5%, Test_loss:0.428,Lr:5.00E-05
==================== Done ====================
Epoch:40, Train_acc:88.0%, Train_loss:0.305, Test_acc:79.5%, Test_loss:0.431,Lr:5.00E-05
==================== Done ====================
Epoch:41, Train_acc:88.0%, Train_loss:0.303, Test_acc:79.5%, Test_loss:0.433,Lr:5.00E-05
==================== Done ====================
Epoch:42, Train_acc:88.1%, Train_loss:0.302, Test_acc:79.5%, Test_loss:0.436,Lr:5.00E-05
==================== Done ====================
Epoch:43, Train_acc:88.2%, Train_loss:0.300, Test_acc:79.5%, Test_loss:0.438,Lr:5.00E-05
==================== Done ====================
Epoch:44, Train_acc:88.4%, Train_loss:0.299, Test_acc:79.5%, Test_loss:0.441,Lr:5.00E-05
==================== Done ====================
Epoch:45, Train_acc:88.4%, Train_loss:0.297, Test_acc:79.5%, Test_loss:0.443,Lr:5.00E-05
==================== Done ====================
Epoch:46, Train_acc:88.7%, Train_loss:0.296, Test_acc:79.5%, Test_loss:0.446,Lr:5.00E-05
==================== Done ====================
Epoch:47, Train_acc:88.8%, Train_loss:0.294, Test_acc:79.5%, Test_loss:0.449,Lr:5.00E-05
==================== Done ====================
Epoch:48, Train_acc:89.0%, Train_loss:0.293, Test_acc:79.1%, Test_loss:0.451,Lr:5.00E-05
==================== Done ====================
Epoch:49, Train_acc:89.1%, Train_loss:0.292, Test_acc:79.1%, Test_loss:0.454,Lr:5.00E-05
==================== Done ====================
Epoch:50, Train_acc:89.2%, Train_loss:0.290, Test_acc:78.6%, Test_loss:0.457,Lr:5.00E-05
==================== Done ====================

九、模型评估

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
epochs_range = range(epochs)
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')plt.show()

十、混淆矩阵

print("==============输入数据Shape为==============")
print("X_test.shape:", X_test.shape)
print("y_test.shape:", y_test.shape)
pred = model(X_test.to(device)).argmax(1).cpu().numpy()
print("\n==============输出数据Shape为==============")
print("pred.shape:", pred.shape)
# 计算混淆矩阵
cm = confusion_matrix(y_test, pred)
plt.figure(figsize=(6, 5))
plt.suptitle('')
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues")
# 修改字体大小
plt.xticks(fontsize=10)
plt.yticks(fontsize=10)
plt.title("Confusion Matrix", fontsize=12)
plt.xlabel("Predicted Label", fontsize=10)
plt.ylabel("True Label", fontsize=10)
# 显示图
plt.tight_layout()  # 调整布局防止重叠plt.show()

 

test_X = X_test[0].reshape(1, -1)  # X_test[0]即我们的输入数据
pred = model(test_X.to(device)).argmax(1).item()
print("模型预测结果为:", pred)
print("==" * 20)
print("0:未患病")
print("1:已患病")

 运行结果:

==============输出数据Shape为==============
pred.shape: (215,)
模型预测结果为: 0
========================================
0:未患病
1:已患病

十一、总结

这周学习RNN实现阿尔茨海默病诊断:

  1. 混淆矩阵概述:

    混淆矩阵是一个二维矩阵,用于总结分类模型在不同类别上的预测结果,包括 True Positive (TP)、False Negative (FN)、False Positive (FP)、True Negative (TN)。
  2. 性能指标:
  • 准确率(Accuracy):模型正确分类的样本占总样本数的比例。
  • 精确率(Precision):模型预测为正类别的样本中有多少是真正的正类别。
  • 召回率(Recall):实际为正类别的样本中,有多少被模型正确预测为正类别。
  • F1 分数:精确率和召回率的调和平均数,综合考虑了查准率和查全率。

       这周新增加了混淆矩阵,它是一个重要且多用途的工具,为我们提供了深入了解分类模型性能的手段,有助于不断改进和优化我们的机器学习应用。


http://www.ppmy.cn/server/152122.html

相关文章

建造者模式(Builder Pattern)

建造者模式(Builder Pattern) 建造者模式是一种 创建型设计模式,它将一个复杂对象的构造与它的表示分离,使得同样的构建过程可以创建不同的表示。 原理 核心思想:通过一步步的构建过程来创建复杂对象,而不…

RK3588平台上YOLOv8模型转换与CentOS 7.8 Docker镜像拉取超时问题解决指南

RK3588平台上YOLOv8模型转换与CentOS 7.8 Docker镜像拉取超时问题解决指南 一、RK3588平台上YOLOv8模型从PT转换为RKNN 背景介绍 YOLOv8的原生模型包含了后处理步骤,其中一些形状超出了RK3588的矩阵计算限制,因此需要对输出层进行一些裁剪。本文将详细…

如何保证开源AI呼入机器人和AI呼出机器人的服务质量?

如何保证开源AI呼入机器人和AI呼出机器人的服务质量? 确保开源AI呼入机器人和AI呼出机器人的服务质量是企业成功部署这些智能系统的关键。高质量的服务不仅能够提高客户满意度,还能增强企业的市场竞争力。以下是实现这一目标的几个关键策略和技术措施&a…

Redis 存储断点续传文件状态的最佳实践

目录 1. Redis 中存储文件上传状态使用 Hash 存储文件状态存储分块上传状态使用 TTL 进行状态过期管理 2. Redis 与数据库保持一致方法 1:定期同步方法 2:实时同步方法 3:双写机制方法 4:系统重启后的恢复 3. 一致性保障4. 总结5.…

用C#(.NET8)开发一个NTP(SNTP)服务

完整源码,附工程下载,工程其实也就下面两个代码。 想在不能上网的服务器局域网中部署一个时间服务NTP,当然系统自带该服务,可以开启,本文只是分享一下该协议报文和能跑的源码。网上作为服务的源码不太常见,…

第十七章:反射+设计模式

一、反射 1. 反射(Reflection):允许在程序运行状态中,可以获取任意类中的属性和方法,并且可以操作任意对象内部的属 性和方法,这种动态获取类的信息及动态操作对象的属性和方法对应的机制称为反射机制。 2. 类对象 和 类的对象(实…

[Unity Shader]【图形渲染】 数学基础4 - 矩阵定义和矩阵运算详解

矩阵是计算机图形学中的重要数学工具,尤其在Shader编程中,它被广泛用于坐标变换、投影变换和模型动画等场景。本文将详细介绍矩阵的定义、基本运算以及如何在Shader中应用矩阵,为初学者打下坚实的数学基础。 一、什么是矩阵? 矩阵是一个由数字排列成的长方形数组,通常记作…

旋转目标检测数据格式转换:RoLabelImg 与 DOTA 格式

引言 在旋转目标检测任务中,数据格式的选择与处理对于模型的训练至关重要。本文将介绍两种常见的旋转目标检测数据格式:RoLabelImg 格式 和 DOTA 格式,并详细说明二者之间的转换方法及其实现代码。 数据格式简介 1. RoLabelImg 格式 RoLa…