- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
一、我的环境
1.语言环境:Python 3.9
2.编译器:Pycharm
3.深度学习环境:pyTorch 2.1.2
二、GPU设置
import torch
# 设置硬件设备,如果有GPU则使用,没有则使用cpu
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
三、数据导入
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import torch.nn as nn
df = 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_split
X = 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, DataLoader
train_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 out
model = 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与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
七、测试函数
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
八、训练模型
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实现阿尔茨海默病诊断:
混淆矩阵概述:
混淆矩阵是一个二维矩阵,用于总结分类模型在不同类别上的预测结果,包括 True Positive (TP)、False Negative (FN)、False Positive (FP)、True Negative (TN)。- 性能指标:
- 准确率(Accuracy):模型正确分类的样本占总样本数的比例。
- 精确率(Precision):模型预测为正类别的样本中有多少是真正的正类别。
- 召回率(Recall):实际为正类别的样本中,有多少被模型正确预测为正类别。
- F1 分数:精确率和召回率的调和平均数,综合考虑了查准率和查全率。
这周新增加了混淆矩阵,它是一个重要且多用途的工具,为我们提供了深入了解分类模型性能的手段,有助于不断改进和优化我们的机器学习应用。