365天深度学习训练营-第P2周:彩色图片识别

该博客记录了使用PyTorch对CIFAR10数据集进行深度学习训练的过程,包括数据预处理、模型搭建、结果可视化。通过DataLoader加载数据,并使用简单的CNN模型,观察训练与验证的准确率和损失变化。
摘要由CSDN通过智能技术生成

>- **🍨 本文为[🔗365天深度学习训练营](https://mp.weixin.qq.com/s/xLjALoOD8HPZcH563En8bQ) 中的学习记录博客**
>- **🍦 参考文章:[365天深度学习训练营-第P2周:彩色识别](https://mp.weixin.qq.com/s/BKsTrlOtu32bQzgORaMLEw)**
>- **🍖 原作者:[K同学啊|接辅导、项目定制](https://mtyjkh.blog.csdn.net/)**

一、 前期准备

1、数据集准备

import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision

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


train_ds = torchvision.datasets.CIFAR10('data',
                                      train=True,
                                      transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
                                      download=True)

test_ds  = torchvision.datasets.CIFAR10('data',
                                      train=False,
                                      transform=torchvision.transforms.ToTensor(), # 将数据类型转化为Tensor
                                      download=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分别是图片的通道数,高度和宽度。
'''  
        print(labels.shape)
        torch.Size([32])
        print(imgs.shape)
        torch.Size([32, 3, 32, 32])
'''

2、数据可视化 

plt.figure(figsize=(20, 5))
for i, imgs in enumerate(imgs[:20]):#image是(32,3,32,32)的Tensor
    # 维度缩减
    '''
    print(imgs.shape)
    torch.Size([3, 32, 32])
    '''

    npimg = imgs.numpy().transpose((1, 2, 0))#Reverse or permute the axes of an array; returns the modified array.

    # 将整个figure分成2行10列,绘制第i+1个子图。
    plt.subplot(2, 10, i+1)
    plt.imshow(npimg, cmap=plt.cm.binary)
    plt.axis('off')
plt.show()

'''
print(imgs.shape)
torch.Size([3, 32, 32])
'''

可以注意到,彩色图片本身是一个三通道的 [32,32]的

transpose()是为了能imshow图片,需要转换成[32 32 3]的彩色图片格式。#Reverse or permute the axes of an array; returns the modified array.

二、模型搭建 

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

            '''
            argmax: Returns the indices of the maximum value of all elements in the input tensor.
            a = torch.randn(4, 4)
            print(a)
            print(torch.argmax(a))
            tensor([[ 0.4275, -1.2385,  1.0918,  1.4491],
                    [ 1.8057,  0.8371,  1.3971,  1.4349],
                    [ 1.1862,  1.7127,  0.8703, -0.3058],
                    [-2.7004,  0.1602,  0.9140, -0.7437]])
                    
            tensor(4)
            
            '''

            '''
            type(torch.float)可以将Tensor中的数据类型转换为float,原本得到是TRUE 和 FALSE的 Tensor 可以成功转化
            
            '''



    test_acc /= size
    test_loss /= num_batches

    return test_acc, test_loss
torch.argmax:
'''
argmax: Returns the indices of the maximum value of all elements in the input tensor.
a = torch.randn(4, 4)
print(a)
print(torch.argmax(a))
tensor([[ 0.4275, -1.2385,  1.0918,  1.4491],
        [ 1.8057,  0.8371,  1.3971,  1.4349],
        [ 1.1862,  1.7127,  0.8703, -0.3058],
        [-2.7004,  0.1602,  0.9140, -0.7437]])
        
tensor(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()

 四、总结

采用和上次实验MNIST一样的CNN卷积网络,但是识别率下降巨大,所以我们有必要采用新的方法来推进图像识别。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

No_one-_-2022

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值