深度学习Day-04:实现猴痘病识别

 🍨 本文为:[🔗365天深度学习训练营] 中的学习记录博客
 🍖 原作者:[K同学啊 | 接辅导、项目定制]

一、 基础配置

  • 语言环境:Python3.8
  • 编译器选择:Pycharm
  • 深度学习环境:
    • torch==1.12.1+cu113
    • torchvision==0.13.1+cu113

二、 前期准备 

1.设置GPU

import torch
import torch.nn as nn
from torchvision import transforms, datasets

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)

根据个人设备情况,选择使用GPU/CPU进行训练,在Pycharm中需要添加print命令来查看是否使用了GPU ,若GPU可用则输出

cuda

2. 导入数据

本项目所采用的数据集未收录于公开数据中,故需要自己在文件目录中导入相应数据集合,并设置对应文件目录,以供后续学习过程中使用。

运行下述代码:

import pathlib

data_dir = 'data'
data_dir = pathlib.Path(data_dir)

data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[1] for path in data_paths]
print(classeNames)

得到如下输出:

['Monkeypox', 'Others']

其中:

  • 第一步:使用pathlib.Path()函数将字符串类型的文件夹路径转换为pathlib.Path对象。
  • 第二步:使用glob()方法获取data_dir路径下的所有文件路径,并以列表形式存储在data_paths中。
  • 第三步:通过split()函数对data_paths中的每个文件路径执行分割操作,获得各个文件所属的类别名称,并存储在classeNames
  • 第四步:打印classeNames列表,显示每个文件所属的类别名称。

由于疾病图片可能会引起不适,故本文中不采用图像可视乎的操作

接下来,我们通过transforms.Compose对整个数据集进行预处理:

  • 第一步:将输入图片resize成统一尺寸,即[224, 224]
  • 第二步:转换为tensor,并归一化到[0,1]之间
  • 第三步:转换为标准正态分布(高斯分布),使模型更容易收敛
total_datadir = 'data'

train_transforms = transforms.Compose([
    transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
    transforms.ToTensor(),          # 转换为tensor,并归一化到[0,1]之间
    transforms.Normalize(           # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225])  # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])

total_data = datasets.ImageFolder(total_datadir,transform=train_transforms)
print(total_data)

 最终,我们可以将整个数据集中的数据处理得到:

Dataset ImageFolder
    Number of datapoints: 2142
    Root location: data
    StandardTransform
Transform: Compose(
               Resize(size=[224, 224], interpolation=bilinear, max_size=None, antialias=None)
               ToTensor()
               Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
           )

接着,我们根据识别的种类对data下的数据类型做了编码处理:

total_data.class_to_idx

3. 划分数据集

将整个数据集按照8:2的比例划分为训练集和测试集:

其中,使用了使用torch.utils.data.random_split()方法进行数据集划分。该方法将总体数据total_data按照指定的大小比例([train_size, test_size])随机划分为训练集和测试集,并将划分结果分别赋值给train_dataset和test_dataset两个变量。

train_size = int(0.8 * len(total_data))
test_size  = len(total_data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])
train_dataset, test_dataset

print(train_size,test_size)

得到如下输出:

1713 429

接着对数据集训练过程中的批次大小进行划分:

对应函数参数说明详见:深度学习Day-01

batch_size = 32

train_dl = torch.utils.data.DataLoader(train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True,
                                           num_workers=0)
test_dl = torch.utils.data.DataLoader(test_dataset,
                                          batch_size=batch_size,
                                          shuffle=True,
                                          num_workers=0)

并通过:

for X, y in test_dl:
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break

 输出整个数据集的数据分布情况:

Shape of X [N, C, H, W]:  torch.Size([32, 3, 224, 224])
Shape of y:  torch.Size([32]) torch.int64

Tips:win需要采用num_workers=0的模式。

4.构建CNN网络

对于一般的CNN网络来说,都是由特征提取网络和分类网络构成,其中特征提取网络用于提取图片的特征,分类网络用于将图片进行分类。

对应函数参数说明详见:深度学习Day-02

  • nn.Conv2d为卷积层,用于提取图片的特征,传入参数为输入channel,输出channel,池化核大小
  • nn.MaxPool2d为池化层,进行下采样,用更高层的抽象表示图像特征,传入参数为池化核大小
  • nn.ReLU为激活函数,使模型可以拟合非线性数据
  • nn.Linear为全连接层,可以起到特征提取器的作用,最后一层的全连接层也可以认为是输出层,传入参数为输入特征数和输出特征数(输入特征数由特征提取网络计算得到,如果不会计算可以直接运行网络,报错中会提示输入特征数的大小,下方网络中第一个全连接层的输入特征数为1600)
  • nn.Sequential可以按构造顺序连接网络,在初始化阶段就设定好网络结构,不需要在前向传播中重新写一遍
import torch.nn.functional as F

class Network_bn(nn.Module):
    def __init__(self):
        super(Network_bn, self).__init__()

        self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=0)
        self.bn1 = nn.BatchNorm2d(12)
        self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=0)
        self.bn2 = nn.BatchNorm2d(12)
        self.pool = nn.MaxPool2d(2,2)
        self.conv4 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=0)
        self.bn4 = nn.BatchNorm2d(24)
        self.conv5 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=0)
        self.bn5 = nn.BatchNorm2d(24)
        self.fc1 = nn.Linear(24*50*50, len(classeNames))

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))      
        x = F.relu(self.bn2(self.conv2(x)))     
        x = self.pool(x)                        
        x = F.relu(self.bn4(self.conv4(x)))     
        x = F.relu(self.bn5(self.conv5(x)))  
        x = self.pool(x)                        
        x = x.view(-1, 24*50*50)
        x = self.fc1(x)

        return x

device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))

model = Network_bn().to(device)
print(model)

Tips:BatchNorm2d 是 PyTorch 中的一个类,用于在卷积神经网络中进行 Batch Normalization 操作。Batch Normalization 是一种常用的正则化技术,用于加速神经网络的训练,并且可以提高模型的泛化能力。

通过运行上述代码,可以得到:

Using cuda device
Network_bn(
  (conv1): Conv2d(3, 12, kernel_size=(5, 5), stride=(1, 1))
  (bn1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (conv2): Conv2d(12, 12, kernel_size=(5, 5), stride=(1, 1))
  (bn2): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv4): Conv2d(12, 24, kernel_size=(5, 5), stride=(1, 1))
  (bn4): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (conv5): Conv2d(24, 24, kernel_size=(5, 5), stride=(1, 1))
  (bn5): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (fc1): Linear(in_features=60000, out_features=2, bias=True)
)

三、 训练模型

1. 设置超参数

loss_fn    = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-4 # 学习率
opt        = torch.optim.SGD(model.parameters(),lr=learn_rate)

这里的三个超参数均可根据要求进行修改,如学习率的数值,优化器的选择等 

2. 编写训练函数

# 训练循环
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小,一共60000张图片
    num_batches = len(dataloader)   # 批次数目,1875(60000/32)

    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

3. 编写测试函数

测试函数和训练函数大致相同,但是由于不进行梯度下降对网络权重进行更新,所以不需要传入优化器

def test (dataloader, model, loss_fn):
    size        = len(dataloader.dataset)  
    num_batches = len(dataloader)         
    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

4. 正式训练

epochs     = 20
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)
    
    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}')
    print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
print('Done')

得到如下输出:

Epoch: 1, Train_acc:60.3%, Train_loss:0.687, Test_acc:66.0%,Test_loss:0.640
Epoch: 2, Train_acc:68.9%, Train_loss:0.593, Test_acc:70.4%,Test_loss:0.587
Epoch: 3, Train_acc:74.8%, Train_loss:0.532, Test_acc:72.5%,Test_loss:0.561
Epoch: 4, Train_acc:76.3%, Train_loss:0.505, Test_acc:69.2%,Test_loss:0.593
Epoch: 5, Train_acc:79.0%, Train_loss:0.467, Test_acc:77.2%,Test_loss:0.506
Epoch: 6, Train_acc:80.6%, Train_loss:0.449, Test_acc:77.2%,Test_loss:0.499
Epoch: 7, Train_acc:81.8%, Train_loss:0.426, Test_acc:76.5%,Test_loss:0.492
Epoch: 8, Train_acc:84.5%, Train_loss:0.401, Test_acc:80.9%,Test_loss:0.472
Epoch: 9, Train_acc:86.0%, Train_loss:0.380, Test_acc:80.7%,Test_loss:0.474
Epoch:10, Train_acc:85.4%, Train_loss:0.372, Test_acc:79.7%,Test_loss:0.467
Epoch:11, Train_acc:86.7%, Train_loss:0.357, Test_acc:76.9%,Test_loss:0.477
Epoch:12, Train_acc:87.3%, Train_loss:0.343, Test_acc:77.6%,Test_loss:0.468
Epoch:13, Train_acc:89.0%, Train_loss:0.324, Test_acc:81.6%,Test_loss:0.431
Epoch:14, Train_acc:88.6%, Train_loss:0.322, Test_acc:81.1%,Test_loss:0.449
Epoch:15, Train_acc:90.2%, Train_loss:0.309, Test_acc:81.6%,Test_loss:0.431
Epoch:16, Train_acc:89.8%, Train_loss:0.301, Test_acc:82.5%,Test_loss:0.421
Epoch:17, Train_acc:89.6%, Train_loss:0.297, Test_acc:83.2%,Test_loss:0.420
Epoch:18, Train_acc:91.0%, Train_loss:0.282, Test_acc:82.8%,Test_loss:0.418
Epoch:19, Train_acc:91.1%, Train_loss:0.277, Test_acc:82.8%,Test_loss:0.406
Epoch:20, Train_acc:92.2%, Train_loss:0.264, Test_acc:81.4%,Test_loss:0.411
Done

四、 结果可视化

1. 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        #分辨率

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

五、保存并加载模型

 为保存训练好的模型,需要向源代码中添加如下代码:

# 模型保存
PATH = './model.pth'  # 保存的参数文件名
torch.save(model.state_dict(), PATH)

# 将参数加载到model当中
model.load_state_dict(torch.load(PATH, map_location=device))

六、个人理解

本项目需要根据所给的图片,来识别猴痘病情况。

1.本项目基础要求中要求保存效果最好的模型参数,因此需要在正式训练前后分别添加:

best_test_acc = 0.0
best_model_weights = None
    if epoch_test_acc > best_test_acc:
        best_test_acc = epoch_test_acc
        best_model_weights = model.state_dict()

 以确保保存的模型为最佳模型。

2.本项目基础要求中要求加载模型并识别一张本地图片,这里我的做法为:

   在main.py同目录下新建了predic.py文件用于加载并预测,防止每次都要运行main.py,代码如下:

import torch
from model import Network_bn,total_data,train_transforms
from PIL import Image

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# 加载模型和权重参数
PATH = './model.pth'  # 保存的参数文件名
model = Network_bn()
model.load_state_dict(torch.load(PATH))
model = model.to(device)

classes = list(total_data.class_to_idx)

def predict_one_image(image_path, model, transform, classes):
    test_img = Image.open(image_path).convert('RGB')

    test_img = transform(test_img)
    img = test_img.to(device).unsqueeze(0)

    model.eval()
    output = model(img)

    _, pred = torch.max(output, 1)
    pred_class = classes[pred]
    print(f'预测结果是:{pred_class}')

# 预测训练集中的某张照片
predict_one_image(image_path='data/Monkeypox/M01_01_00.jpg',
                  model=model,
                  transform=train_transforms,
                  classes=classes)

得到如下结果:

预测结果是:Monkeypox

3.项目要求修改参数使得准确率达到88%以上,这里修改了epoch(30)、batch_size(64)和优化器(Adam),实现精度为90.2%,具体精度迭代过程如下:

Epoch: 1, Train_acc:62.5%, Train_loss:0.849, Test_acc:70.9%,Test_loss:0.596
Epoch: 2, Train_acc:78.6%, Train_loss:0.472, Test_acc:78.8%,Test_loss:0.471
Epoch: 3, Train_acc:84.8%, Train_loss:0.378, Test_acc:79.7%,Test_loss:0.440
Epoch: 4, Train_acc:88.6%, Train_loss:0.301, Test_acc:81.1%,Test_loss:0.431
Epoch: 5, Train_acc:92.0%, Train_loss:0.246, Test_acc:85.3%,Test_loss:0.348
Epoch: 6, Train_acc:92.9%, Train_loss:0.207, Test_acc:86.0%,Test_loss:0.328
Epoch: 7, Train_acc:94.7%, Train_loss:0.179, Test_acc:86.2%,Test_loss:0.332
Epoch: 8, Train_acc:94.2%, Train_loss:0.166, Test_acc:87.4%,Test_loss:0.319
Epoch: 9, Train_acc:97.3%, Train_loss:0.123, Test_acc:88.6%,Test_loss:0.288
Epoch:10, Train_acc:97.8%, Train_loss:0.104, Test_acc:88.6%,Test_loss:0.280
Epoch:11, Train_acc:98.1%, Train_loss:0.097, Test_acc:86.7%,Test_loss:0.301
Epoch:12, Train_acc:98.1%, Train_loss:0.090, Test_acc:89.0%,Test_loss:0.276
Epoch:13, Train_acc:98.7%, Train_loss:0.077, Test_acc:89.7%,Test_loss:0.256
Epoch:14, Train_acc:98.3%, Train_loss:0.074, Test_acc:89.7%,Test_loss:0.266
Epoch:15, Train_acc:99.5%, Train_loss:0.053, Test_acc:89.5%,Test_loss:0.251
Epoch:16, Train_acc:99.3%, Train_loss:0.049, Test_acc:89.7%,Test_loss:0.262
Epoch:17, Train_acc:99.6%, Train_loss:0.043, Test_acc:90.2%,Test_loss:0.260
Epoch:18, Train_acc:99.9%, Train_loss:0.033, Test_acc:89.7%,Test_loss:0.251
Epoch:19, Train_acc:99.7%, Train_loss:0.038, Test_acc:90.0%,Test_loss:0.248
Epoch:20, Train_acc:99.9%, Train_loss:0.028, Test_acc:89.7%,Test_loss:0.285
Epoch:21, Train_acc:99.7%, Train_loss:0.026, Test_acc:89.3%,Test_loss:0.253
Epoch:22, Train_acc:99.9%, Train_loss:0.025, Test_acc:90.2%,Test_loss:0.254
Epoch:23, Train_acc:100.0%, Train_loss:0.022, Test_acc:90.0%,Test_loss:0.255
Epoch:24, Train_acc:100.0%, Train_loss:0.019, Test_acc:90.9%,Test_loss:0.262
Epoch:25, Train_acc:99.9%, Train_loss:0.018, Test_acc:90.9%,Test_loss:0.266
Epoch:26, Train_acc:100.0%, Train_loss:0.016, Test_acc:89.5%,Test_loss:0.270
Epoch:27, Train_acc:100.0%, Train_loss:0.014, Test_acc:90.4%,Test_loss:0.266
Epoch:28, Train_acc:100.0%, Train_loss:0.014, Test_acc:90.4%,Test_loss:0.259
Epoch:29, Train_acc:100.0%, Train_loss:0.014, Test_acc:89.3%,Test_loss:0.299
Epoch:30, Train_acc:100.0%, Train_loss:0.012, Test_acc:90.2%,Test_loss:0.258
Done

根据项目拔高要求(目前部分实现,未完成部分将在后续学习过程中更新):

  1. 调整模型参数并观察测试集的准确率变化;
  2. 尝试设置动态学习率;
  3. 测试集accuracy到达90%(已实现)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值