第R8周:RNN实现阿尔兹海默病诊断

发布于:2025-03-17 ⋅ 阅读:(20) ⋅ 点赞:(0)

电脑环境:
语言环境:Python 3.8.0
深度学习:torch 2.5.1+cu124

1、设置GPU

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import torch
import torch.nn as nn
import torch.nn.functional as F

# 设置GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)

2、导入数据

df = pd.read_csv('/alzheimers_disease_data.csv')
# 删除最后一列和第一列
df = df.iloc[:, 1:-1]
df.head()
	Age	Gender	Ethnicity	EducationLevel	BMI	Smoking	AlcoholConsumption	PhysicalActivity	DietQuality	SleepQuality	...	FunctionalAssessment	MemoryComplaints	BehavioralProblems	ADL	Confusion	Disorientation	PersonalityChanges	DifficultyCompletingTasks	Forgetfulness	Diagnosis
0	73	0	0	2	22.927749	0	13.297218	6.327112	1.347214	9.025679	...	6.518877	0	0	1.725883	0	0	0	1	0	0
1	89	0	0	0	26.827681	0	4.542524	7.619885	0.518767	7.151293	...	7.118696	0	0	2.592424	0	0	0	0	1	0
2	73	0	3	1	17.795882	0	19.555085	7.844988	1.826335	9.673574	...	5.895077	0	0	7.119548	0	1	0	1	0	0
3	74	1	0	1	33.800817	1	12.209266	8.428001	7.435604	8.392554	...	8.965106	0	1	6.481226	0	0	0	0	0	0
4	89	0	0	0	20.716974	0	18.454356	6.310461	0.795498	5.597238	...	6.045039	0	0	0.014691	0	0	1	1	0	0
5 rows × 33 columns

3、数据标准化

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

X = df.iloc[:, :-1]
y = df.iloc[:, -1]

# 将每一列特征标准化为标准正态分布,注意,标准化是针对每一列而言的
scaler = StandardScaler()
X = scaler.fit_transform(X)

4、划分数据集

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)

X_train.shape, y_train.shape

5、构建数据加载器

from torch.utils.data import TensorDataset, DataLoader

train_dl = DataLoader(TensorDataset(X_train, y_train), 
                      batch_size=32, 
                      shuffle=False)
test_dl = DataLoader(TensorDataset(X_test, y_test), 
                     batch_size=32, 
                     shuffle=False)

6、模型构建

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 out

model = model_rnn().to(device)
model

7、定义训练函数

# 训练循环
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与loss
        train_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    train_acc  /= size
    train_loss /= num_batches

    return train_acc, train_loss

8、定义测试函数

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)

            # 计算loss
            target_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  /= size
    test_loss /= num_batches

    return test_acc, test_loss

9、正式训练

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('Done')
Epoch: 1, Train_acc:61.4%, Train_loss:0.672, Test_acc:65.1%, Test_loss:0.656, Lr:5.00E-05
Epoch: 2, Train_acc:67.3%, Train_loss:0.629, Test_acc:65.6%, Test_loss:0.622, Lr:5.00E-05
Epoch: 3, Train_acc:67.1%, Train_loss:0.592, Test_acc:66.5%, Test_loss:0.597, Lr:5.00E-05
Epoch: 4, Train_acc:69.5%, Train_loss:0.560, Test_acc:67.4%, Test_loss:0.571, Lr:5.00E-05
Epoch: 5, Train_acc:74.1%, Train_loss:0.528, Test_acc:70.7%, Test_loss:0.544, Lr:5.00E-05
Epoch: 6, Train_acc:78.5%, Train_loss:0.494, Test_acc:74.9%, Test_loss:0.517, Lr:5.00E-05
Epoch: 7, Train_acc:81.6%, Train_loss:0.463, Test_acc:76.3%, Test_loss:0.493, Lr:5.00E-05
Epoch: 8, Train_acc:83.1%, Train_loss:0.435, Test_acc:76.3%, Test_loss:0.472, Lr:5.00E-05
Epoch: 9, Train_acc:83.9%, Train_loss:0.412, Test_acc:77.7%, Test_loss:0.455, Lr:5.00E-05
Epoch:10, Train_acc:84.8%, Train_loss:0.394, Test_acc:80.0%, Test_loss:0.442, Lr:5.00E-05
Epoch:11, Train_acc:85.1%, Train_loss:0.380, Test_acc:80.9%, Test_loss:0.432, Lr:5.00E-05
Epoch:12, Train_acc:85.3%, Train_loss:0.368, Test_acc:80.5%, Test_loss:0.425, Lr:5.00E-05
Epoch:13, Train_acc:85.4%, Train_loss:0.360, Test_acc:80.0%, Test_loss:0.420, Lr:5.00E-05
Epoch:14, Train_acc:85.7%, Train_loss:0.353, Test_acc:79.5%, Test_loss:0.417, Lr:5.00E-05
Epoch:15, Train_acc:86.1%, Train_loss:0.347, Test_acc:79.5%, Test_loss:0.415, Lr:5.00E-05
Epoch:16, Train_acc:86.4%, Train_loss:0.342, Test_acc:79.5%, Test_loss:0.414, Lr:5.00E-05
Epoch:17, Train_acc:86.8%, Train_loss:0.338, Test_acc:79.1%, Test_loss:0.414, Lr:5.00E-05
Epoch:18, Train_acc:87.0%, Train_loss:0.335, Test_acc:78.1%, Test_loss:0.415, Lr:5.00E-05
Epoch:19, Train_acc:87.0%, Train_loss:0.331, Test_acc:77.2%, Test_loss:0.416, Lr:5.00E-05
Epoch:20, Train_acc:87.1%, Train_loss:0.329, Test_acc:76.7%, Test_loss:0.418, Lr:5.00E-05
Epoch:21, Train_acc:87.1%, Train_loss:0.326, Test_acc:76.7%, Test_loss:0.420, Lr:5.00E-05
Epoch:22, Train_acc:87.2%, Train_loss:0.323, Test_acc:77.7%, Test_loss:0.423, Lr:5.00E-05
Epoch:23, Train_acc:87.0%, Train_loss:0.321, Test_acc:77.7%, Test_loss:0.425, Lr:5.00E-05
Epoch:24, Train_acc:87.3%, Train_loss:0.319, Test_acc:77.7%, Test_loss:0.428, Lr:5.00E-05
Epoch:25, Train_acc:87.2%, Train_loss:0.317, Test_acc:78.1%, Test_loss:0.431, Lr:5.00E-05
Epoch:26, Train_acc:87.3%, Train_loss:0.315, Test_acc:77.7%, Test_loss:0.433, Lr:5.00E-05
Epoch:27, Train_acc:87.4%, Train_loss:0.313, Test_acc:78.1%, Test_loss:0.436, Lr:5.00E-05
Epoch:28, Train_acc:87.5%, Train_loss:0.311, Test_acc:77.7%, Test_loss:0.439, Lr:5.00E-05
Epoch:29, Train_acc:87.5%, Train_loss:0.310, Test_acc:78.1%, Test_loss:0.441, Lr:5.00E-05
Epoch:30, Train_acc:87.7%, Train_loss:0.308, Test_acc:78.1%, Test_loss:0.444, Lr:5.00E-05
Epoch:31, Train_acc:87.7%, Train_loss:0.306, Test_acc:78.6%, Test_loss:0.447, Lr:5.00E-05
Epoch:32, Train_acc:87.9%, Train_loss:0.305, Test_acc:76.7%, Test_loss:0.449, Lr:5.00E-05
Epoch:33, Train_acc:88.0%, Train_loss:0.303, Test_acc:76.3%, Test_loss:0.452, Lr:5.00E-05
Epoch:34, Train_acc:88.0%, Train_loss:0.301, Test_acc:75.8%, Test_loss:0.454, Lr:5.00E-05
Epoch:35, Train_acc:88.1%, Train_loss:0.300, Test_acc:76.3%, Test_loss:0.457, Lr:5.00E-05
Epoch:36, Train_acc:88.2%, Train_loss:0.298, Test_acc:76.3%, Test_loss:0.460, Lr:5.00E-05
Epoch:37, Train_acc:88.4%, Train_loss:0.296, Test_acc:77.2%, Test_loss:0.462, Lr:5.00E-05
Epoch:38, Train_acc:88.6%, Train_loss:0.294, Test_acc:77.2%, Test_loss:0.465, Lr:5.00E-05
Epoch:39, Train_acc:88.7%, Train_loss:0.293, Test_acc:77.2%, Test_loss:0.468, Lr:5.00E-05
Epoch:40, Train_acc:88.8%, Train_loss:0.291, Test_acc:77.2%, Test_loss:0.471, Lr:5.00E-05
Epoch:41, Train_acc:88.8%, Train_loss:0.289, Test_acc:77.2%, Test_loss:0.475, Lr:5.00E-05
Epoch:42, Train_acc:89.0%, Train_loss:0.287, Test_acc:77.2%, Test_loss:0.478, Lr:5.00E-05
Epoch:43, Train_acc:88.9%, Train_loss:0.285, Test_acc:77.7%, Test_loss:0.481, Lr:5.00E-05
Epoch:44, Train_acc:88.9%, Train_loss:0.283, Test_acc:77.7%, Test_loss:0.485, Lr:5.00E-05
Epoch:45, Train_acc:89.0%, Train_loss:0.282, Test_acc:78.1%, Test_loss:0.489, Lr:5.00E-05
Epoch:46, Train_acc:89.0%, Train_loss:0.280, Test_acc:78.1%, Test_loss:0.493, Lr:5.00E-05
Epoch:47, Train_acc:89.2%, Train_loss:0.278, Test_acc:78.1%, Test_loss:0.497, Lr:5.00E-05
Epoch:48, Train_acc:89.4%, Train_loss:0.276, Test_acc:78.1%, Test_loss:0.501, Lr:5.00E-05
Epoch:49, Train_acc:89.6%, Train_loss:0.274, Test_acc:78.6%, Test_loss:0.506, Lr:5.00E-05
Epoch:50, Train_acc:89.6%, Train_loss:0.272, Test_acc:78.1%, Test_loss:0.510, Lr:5.00E-05
Done

10、Loss与Accuracy图

import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore")               #忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        #分辨率

from datetime import datetime
current_time = datetime.now()

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.xlabel(current_time)

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

在这里插入图片描述

11、混淆矩阵

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("====================输出数据Shape为====================")
print("pred.shape: ",pred.shape)

输入数据Shape为
X_test.shape: torch.Size([215, 32])
y_test.shape: torch.Size([215])
输出数据Shape为
pred.shape: (215,)

import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

# 计算混淆矩阵
cm = confusion_matrix(y_test, pred)

plt.figure(figsize=(6,5))
# plt.suptitle('Confusion Matrix')
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')

# 修改字体大小
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.title('Confusion Matrix', fontsize=12)
plt.xlabel('Predicted Label', fontsize=12)
plt.ylabel('True Labels', fontsize=10)

# 调整布局防止重叠
plt.tight_layout()

# 显示图形
plt.show()

在这里插入图片描述

12、调用模型进行预测

# 调用模型进行预测
test_X = X_test[0].reshape(1, -1)

pred = model(test_X.to(device)).argmax(1).item()
print("模型预测结果为: ",pred)
print("="*20)
print("0: 未患病")
print("1: 已患病")

输出:

模型预测结果为:  0
====================
0: 未患病
1: 已患病