当前位置: 首页 > article >正文

第P4周-Pytorch实现猴痘病识别

  • 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍖 原作者:K同学啊

目标

具体实现

(一)环境

语言环境:Python 3.10
编 译 器: PyCharm
框 架: Pytorch

(二)具体步骤
1. Utils.py
import torch  
import pathlib  
import matplotlib.pyplot as plt  
  
# 第一步:设置GPU  
def USE_GPU():  
    if torch.cuda.is_available():  
        print('CUDA is available, will use GPU')  
        device = torch.device("cuda")  
    else:  
        print('CUDA is not available. Will use CPU')  
        device = torch.device("cpu")  
  
    return device  
  
def data_from_directory(directory, show=True):  
    """  
    提供是的数据集是文件形式的,提供目录方式导入数据,简单分析数据并返回数据分类  
    :param directory: 数据集所在目录  
    :param show: 是否需要以柱状图形式显示数据分类情况,默认显示  
    :return: 数据分类列表,类型: list  
    """    print("数据目录:{}".format(directory))  
    data_dir = pathlib.Path(directory)  
  
    data_path = list(data_dir.glob('*'))  
    class_name = [str(path).split('\\')[-1] for path in data_path]  
    print("数据分类: {}, 类别数量:{}".format(class_name, len(list(data_dir.glob('*')))))  
    total_image = len(list(data_dir.glob('*/*')))  
    print("图片数据总数: {}".format(total_image))  
  
    temp_sum = 0  
    if show:  
        # 隐藏警告  
        import warnings  
        warnings.filterwarnings("ignore")  # 忽略警告信息  
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签  
        plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号  
        plt.rcParams['figure.dpi'] = 100  # 分辨率  
  
        for i in class_name:  
            data = len(list(pathlib.Path((directory + '\\' + i + '\\')).glob('*')))  
            plt.title('数据分类情况')  
            plt.grid(ls='--', alpha=0.5)  
            plt.bar(i, data)  
            plt.text(i, data, str(data), ha='center', va='bottom')  
            print("类别-{}:{}".format(i, data))  
            temp_sum += data  
        plt.show()  
  
    if temp_sum == total_image:  
        print("图片数据总数检查一致")  
    else:  
        print("数据数据总数检查不一致,请检查数据集是否正确!")  
    return class_name
2. model.py
import torch.nn as nn  
import torch

mport torch.nn.functional as F  
  
class Network_bn(nn.Module):  
    def __init__(self, classNames):  
        super(Network_bn, self).__init__()  
        """  
        nn.Conv2d()函数:  
        第一个参数(in_channels)是输入的channel数量  
        第二个参数(out_channels)是输出的channel数量  
        第三个参数(kernel_size)是卷积核大小  
        第四个参数(stride)是步长,默认为1  
        第五个参数(padding)是填充大小,默认为0  
        """        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(classNames))  
  
    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
3. main.py
from mpmath.identification import transforms  
from torch import nn  
  
from Utils import USE_GPU, data_from_directory  
from model import Network_bn  
import torch  
import torchvision  
from torchvision import transforms, datasets  
import os, PIL, pathlib  
import matplotlib.pyplot as plt  
  
  
  
device = USE_GPU()  
  
DATA_DIR = "./data/monkeypox"  
class_names = data_from_directory(DATA_DIR)  

image.png

image.png

  
train_transforms = transforms.Compose([  
    transforms.Resize((224, 224)),  
    transforms.ToTensor(),  
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])  
])  
  
total_data = datasets.ImageFolder(DATA_DIR, transform=train_transforms)  
print(total_data)  
print(total_data.class_to_idx)  
  
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])  
print(train_dataset, test_dataset)  
print("train size: {}, test size: {}".format(train_size, test_size))  
  
batch_size = 32  
train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)  
test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True)  
  
for X, y in train_dataloader:  
    print("Shape of X[N, C, H, W]: ", X.shape)  
    print("Shape of y: ", y.shape)  
    break  
  
  
model = Network_bn(class_names).to(device)  
print(model)  

image.png

loss_fn = nn.CrossEntropyLoss()  
learn_rate = 1e-4  
optimizer = torch.optim.SGD(model.parameters(), lr=learn_rate)  
  
def train(dataloader, model, loss_fn, optimizer):  
    size = len(dataloader.dataset)  
    num_batches = len(dataloader)  
  
    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)  
  
        optimizer.zero_grad()  
        loss.backward()  
        optimizer.step()  
  
        train_loss += loss.item()  
        train_acc += (pred.argmax(1) == y).type(torch.float).sum().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)  
    test_loss, test_acc = 0, 0  
  
    with torch.no_grad():  
        for imgs, targets in dataloader:  
            imgs, targets = imgs.to(device), targets.to(device)  
  
            target_pred = model(imgs)  
            loss = loss_fn(target_pred, targets)  
  
            test_loss += loss.item()  
            test_acc += (target_pred.argmax(1) == targets).type(torch.float).sum().item()  
  
    test_acc /= size  
    test_loss /= num_batches  
  
    return test_acc, test_loss  
  
  
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_dataloader, model, loss_fn, optimizer)  
  
    model.eval()  
    epoch_test_acc, epoch_test_loss = test(test_dataloader, model, loss_fn)  
  
    train_acc.append(epoch_train_acc)  
    test_acc.append(epoch_test_acc)  
    train_loss.append(epoch_train_loss)  
    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')

image.png


http://www.kler.cn/a/468632.html

相关文章:

  • 【HarmonyOS-ArkTS语言】计算器的实现【合集】
  • 【Qt】控件概述和QWidget核心属性1(enabled、geometry、windowTitle、windowIcon、QRC机制)
  • github开源链游详细搭建文档
  • 前端学习DAY31(子元素溢出父元素)
  • 自动采集商品信息、处理数据并自动上架到
  • SUB输入5V升压充电16.8V芯片HU5912
  • leetcode(hot100)4
  • C++编程等级认证学习计划
  • 一种可复用的AI提效方案:AI点灯
  • Springboot项目部署以及jar包属性配置
  • 分类、聚类与回归的评价指标
  • 【NLP高频面题 - 分布式训练篇】ZeRO主要为了解决什么问题?
  • CSS——10.类选择器
  • 【Go学习】-01-6-数据库泛型新特性
  • 如何处理外在关系以及内在关系,思维冲突和纠结
  • 挑战20天刷完leecode100
  • C语言程序设计(第5版)习题解答-第4章
  • stm32HAL库使LED闪烁
  • ArcGIS中怎么把数据提取到指定范围(裁剪、掩膜提取)
  • RabbitMQ-基本使用
  • ChatGPT 主流模型GPT-4/GPT-4o mini的参数规模是多大?
  • 学习扩散模型的完整指南(前提知识、DDPM、稳定扩散、DreamBooth等)
  • php有两个数组map比较 通过id关联,number可能数量变化 比较他们之间增加修改删除
  • 【机器学习:二、线性回归模型】
  • 前端(API)学习笔记(CLASS 4):进阶
  • Unity3D 如何做好项目性能优化详解