>- **🍨 本文为[🔗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卷积网络,但是识别率下降巨大,所以我们有必要采用新的方法来推进图像识别。