深度学习训练营PyTorch week1

  • P1周:mnist手写数字识别

我的环境:

  • OS: win 10 pro
  • 语言环境:Python 3.12.2
  • 平台:Google Colab
  • 深度学习环境:
    • torch = 2.2.2
    • torchvision = 0.17.2

前期准备:

1.设置GPU

我的设备上只有cpu可用

import torch
import torch.nn as nn
import matplotlib.pyplot as plt #需要提前download matplotlib module
import torchvision
print(torch.__version__)
print(torchvision.__version__)
# 设置硬件设备,如果有GPU则使用,没有则使用cpu
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device
2.2.2
0.17.2





device(type='cpu')
2.导入数据

dataset:下载MNIST数据集,划分 training data & testing data

dataloader:加载数据并设置基本batch_size

torch模块:

torch模块是PyTorch的核心模块,提供了Tensor计算和自动求导等基本功能。它包括了Tensor操作、数学函数、优化算法等基础工具,是构建和训练深度学习模型的基础。torch模块提供了丰富的张量操作,例如张量的创建、索引、切片、数学运算、线性代数运算等。它还提供了自动求导功能,可以自动计算张量操作的梯度,并用于反向传播算法。

torchvision模块:

torchvision模块是PyTorch的一个独立模块,主要用于计算机视觉任务。它提供了一系列用于处理图像和视频数据的工具和函数,包括数据加载、数据变换、模型架构等。torchvision集成了一些常用的计算机视觉数据集,例如MNIST、CIFAR-10等,以及一些经典的预训练模型,如AlexNet、ResNet等。它还提供了各种数据变换操作,如随机裁剪、图像翻转、标准化等,方便用户对图像数据进行预处理。除了数据加载和预处理,torchvision还提供了一些计算机视觉模型的定义和训练方法,使得用户可以方便地进行图像分类、目标检测、图像生成等任务的开发和研究。

函数原型

torchvision.datasets.MNIST(root: Union[str, Path], train: bool = True, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, download: bool = False)

参数

  • root (str or pathlib.Path) – Root directory of dataset where MNIST/raw/train-images-idx3-ubyte and MNIST/raw/t10k-images-idx3-ubyte exist.

  • train (bool, optional) – If True, creates dataset from train-images-idx3-ubyte[训练集图像], otherwise from t10k-images-idx3-ubyte[测试集图像].

  • download (bool, optional) – If True, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again.

  • transform (callable, optional) – A function/transform that takes in a PIL image and returns a transformed version. E.g, transforms.RandomCrop

  • target_transform (callable, optional) – A function/transform that takes in the target and transforms it.

train_ds = torchvision.datasets.MNIST("data", train = True,
                    transform = torchvision.transforms.ToTensor(),#将数据类型转化为tensor
                    download=True)
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz


10.2%

Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to data\MNIST\raw\train-images-idx3-ubyte.gz


100.0%


Extracting data\MNIST\raw\train-images-idx3-ubyte.gz to data\MNIST\raw


100.0%


Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to data\MNIST\raw\train-labels-idx1-ubyte.gz
Extracting data\MNIST\raw\train-labels-idx1-ubyte.gz to data\MNIST\raw

Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to data\MNIST\raw\t10k-images-idx3-ubyte.gz



100.0%
100.0%


Extracting data\MNIST\raw\t10k-images-idx3-ubyte.gz to data\MNIST\raw

Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to data\MNIST\raw\t10k-labels-idx1-ubyte.gz
Extracting data\MNIST\raw\t10k-labels-idx1-ubyte.gz to data\MNIST\raw
test_ds = torchvision.datasets.MNIST("data",train = False,
                    transform=torchvision.transforms.ToTensor(),#将数据类型转化为tensor
                     download=True)

torch.utils.data.DataLoader

是PyToch自带的数据加载器,结合数据集和取样器,并且提供多个线程处理数据集

函数原型

torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=None, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, multiprocessing_context=None, generator=None, *, prefetch_factor=None, persistent_workers=False, pin_memory_device=‘’)

参数说明

  • dataset (Dataset) – dataset from which to load the data.

  • batch_size (int, optional) – 定义每batch加载的样本数(默认:1)

  • shuffle (bool, optional) – 若为True,每epoch重新排列数据.默认:False

  • sampler (Sampler or Iterable, optional) – 定义从数据集中提取样本的策略。可以是任何实现了 __ len __ 的 Iterable。如果指定,则不得指定 shuffle。

  • batch_sampler (Sampler or Iterable, optional) – 和sampler类似,但是一次返回一批索引,与 batch_size、shuffle、sampler 和 drop_last互斥。

  • num_workers (int, optional) – 用于数据加载的子进程数。0表示数据将在主进程中加载(默认:0)

  • collate_fn (Callable, optional) – 合并样本列表,形成一个小型批次的Tensors。在使用地图式数据集批量加载时使用。

  • pin_memory (bool, optional) – 如果为True,数据加载器将在返回之前将张量复制到设备/CUDA 固定内存中。如果数据元素是自定义类型,或者collate_fn返回一个自定义类型的批次。官网处有示例

  • drop_last (bool, optional) – 设置为 True 时,如果数据集大小不能被批次大小整除,则放弃最后一个未完成的批次。如果设置为 “假”,且数据集大小不能被批次大小整除,则最后一批数据会更小。(默认值:假)

  • timeout (numeric, optional) – 设置数据读取的超时时间 , 超过这个时间还没读取到数据的话就会报错。(默认值:0)

  • worker_init_fn (Callable, optional) – 如果不是 None,这将在步长之后和数据加载之前在每个工作子进程上调用,并使用工作 id([0,num_workers - 1] 中的一个 int)的顺序逐个导入。(默认:None)

  • multiprocessing_context (str or multiprocessing.context.BaseContext, optional) – 如果为"None",则将使用操作系统的默认多进程上下文。(默认值:None)

  • generator (torch.Generator, optional) – If 如果不是"None",RandomSampler 将使用该 RNG 生成随机索引,而 multiprocessing 将使用该 RNG 为 Worker 生成 base_seed。(默认值:None)

  • prefetch_factor (int, optional, keyword-only arg) – 每个worker预先加载的批次数量。2 表示所有workers将预取总共2*num_workers的批次。(默认值取决于 num_workers的设置值。如果num_worker的值=0,默认值为 “None”。否则,如果num_workers的值>0,则默认值为2)。

  • persistent_workers (bool, optional) – 如果为 True,data loader将不会在数据集被消耗一次后关闭工作者进程。这样就能保持工作数据集实例处于活动状态。(默认值:False)

  • pin_memory_device (str, optional) – 如果pin_memory是True,即为要发送的设备

batch_size = 32
train_dl = torch.utils.data.DataLoader(train_ds, batch_size=batch_size, shuffle = True)
test_dl = torch.utils.data.DataLoader(test_ds, batch_size=batch_size)
# 取一个批次查看数据格式
# 数据的shape为:[batch_size, channel, height, weight]
# 其中batch_size为自己设定,channel,height和weight分别是图片的通道数,高度和宽度。
# 因为是黑白图片故channel为1
imgs, labels = next(iter(train_dl))
print(imgs.shape)
print(labels.shape)
torch.Size([32, 1, 28, 28])
torch.Size([32])
  1. **train_dl**是一个 PyTorch 数据加载器(DataLoader),用于加载训练数据集。通常情况下,数据加载器会将数据集分成小批量(batches)进行处理。
  2. iter(train_dl)将数据加载器转换为一个迭代器(iterator),使得我们可以使用 Python的next() 函数来逐个访问数据加载器中的元素。
  3. **next()**函数用于获取迭代器中的下一个元素。在这里,它被用来获取train_dl中的下一个批量数据。
  4. imgs, labels = ... 这行代码是 Python 的解构赋值语法。它将从 next() 函数返回的元素中提取出两个变量:imgs 和 labels。
  5. imgs变量将包含一个批量的图像数据,而 labels 变量将包含相应的标签数据。这些图像和标签是从训练数据集中提取的。
3.数据可视化

squeeze()函数的功能是从矩阵shape中,去掉维度为1的。例如一个矩阵的shape是(5, 1),使用过这个函数后,结果为(5, )。

import numpy as np

 # 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch)
plt.figure(figsize=(20, 5))
for i, imgs in enumerate(imgs[:20]):
    # 维度缩减
    npimg = np.squeeze(imgs.numpy())
    # 将整个figure分成2行10列,绘制第i+1个子图。
    plt.subplot(2, 10, i+1)
    plt.imshow(npimg, cmap=plt.cm.binary)
    plt.axis('off')

#plt.show()  如果你使用的是Pycharm编译器,请加上这行代码

这里插入图片描述

2.构建简单的CNN

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

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

num_classes = 10  # 图片的类别数

class Model(nn.Module):
     def __init__(self):
        super().__init__()
         # 特征提取网络
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3)  # 第一层卷积,卷积核大小为3*3
        self.pool1 = nn.MaxPool2d(2)           # 设置池化层,池化核大小为2*2
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3) # 第二层卷积,卷积核大小为3*3
        self.pool2 = nn.MaxPool2d(2)

        # 分类网络
        self.fc1 = nn.Linear(1600, 64)
        self.fc2 = nn.Linear(64, num_classes)
     # 前向传播
     def forward(self, x):
        x = self.pool1(F.relu(self.conv1(x)))
        x = self.pool2(F.relu(self.conv2(x)))

        x = torch.flatten(x, start_dim=1)

        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return x
import torchinfo
from torchinfo import summary
# 将模型转移到GPU中(我们模型运行均在GPU中进行)
model = Model().to(device)

summary(model)
=================================================================
Layer (type:depth-idx)                   Param #
=================================================================
Model                                    --
├─Conv2d: 1-1                            320
├─MaxPool2d: 1-2                         --
├─Conv2d: 1-3                            18,496
├─MaxPool2d: 1-4                         --
├─Linear: 1-5                            102,464
├─Linear: 1-6                            650
=================================================================
Total params: 121,930
Trainable params: 121,930
Non-trainable params: 0
=================================================================

3.训练模型

1)设置超参数
loss_fn    = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-2 # 学习率
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)  # 测试集的大小,一共10000张图片
    num_batches = len(dataloader)          # 批次数目,313(10000/32=312.5,向上取整)
    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     = 5
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:94.2%, Train_loss:0.190, Test_acc:95.0%,Test_loss:0.155
Epoch: 2, Train_acc:96.4%, Train_loss:0.120, Test_acc:96.8%,Test_loss:0.101
Epoch: 3, Train_acc:97.2%, Train_loss:0.091, Test_acc:97.9%,Test_loss:0.070
Epoch: 4, Train_acc:97.7%, Train_loss:0.076, Test_acc:97.8%,Test_loss:0.068
Epoch: 5, Train_acc:98.0%, Train_loss:0.066, Test_acc:97.5%,Test_loss:0.079
Done

4.结果可视化

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

在这里插入图片描述

学习感想:

  • 跑了一遍程序但很多地方仍没有完全理解;需要加强一些代码基础;
  • 简单了解了pytorch中的dataset和dataloader两类以及下载和加载数据集的函数
  • 学会划分数据集和了解CNN网络的基本结构,但对于许多概念还不理解,以及卷积核、池化核
  • 计划后续额外补充关于ML的基础概念
  • 26
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值