- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍦 参考文章:365天深度学习训练营-第P2周:彩色识别
- 🍖 原作者:K同学啊|接辅导、项目定制
📌第P3周:天气识别📌
难度:新手入门⭐
语言:Python3、Pytorch
🍺 要求:
1.本地读取并加载数据
2.测试集accuracy到达93%
🔔拔高:
1.测试集accuracy到达95%
2.调用模型识别一张本地图片
一、前期准备
1.设置GPU
如果设备上支持GPU就使用GPU,否则使用CPU
In [1]
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from torchvision import transforms, datasets
import os,PIL,pathlib
import numpy as np
import matplotlib.pyplot as plt
import warnings
In [2]
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
device
2.导入数据
In [3]
data_dir = 'data/weather'
classeNames = os.listdir(data_dir)
classeNames
Out [3]
['cloudy', 'rain', 'shine', 'sunrise']
In [4]
transforms = transforms.Compose([
transforms.Resize((224, 224)), # 将输入图片resize成统一尺寸
transforms.ToTensor(), # 将PIL Image(w,h)或numpy.ndarray(h,w,c)转换为tensor(c,h,w),并将每个像素值归一化到[0,1]之间
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
])
total_dataset = datasets.ImageFolder(data_dir, transform=transforms)
total_dataset
3.划分数据集
In [5]
train_size = int(len(total_dataset) * 0.8)
test_size = len(total_dataset) - train_size
train_size, test_size
In [6]
# 构建dataset
train_dataset, test_dataset = torch.utils.data.random_split(total_dataset, [train_size, test_size])
train_dataset, test_dataset
In [7]
# 构建dataloader
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size,
shuffle=True,
)
test_dl = torch.utils.data.DataLoader(test_dataset,
batch_size=batch_size,
)
In [8]
X, label = next(iter(train_dl)) # 取出一个批次的数据
X.shape, label.shape
4.数据可视化
In [9]
# 指定图片大小,图像大小为20宽、5高的绘图(单位为英寸inch)
plt.figure(figsize=(20, 5))
# 把图像和目标标签组合成一个列表
images_and_labels = list(zip(X, label))
for i, (img, label) in enumerate(images_and_labels[:20]): # 取一个批次中的前20张
# 反标准化
img = img / 2 + 0.5
# 把tensor换成ndarray并进行维度变换
img = np.transpose(img.numpy(), (1, 2, 0))
# 将整个figure分成2行10列,绘制第i+1个子图。
plt.subplot(2, 10, i+1)
plt.title('label: ' + str(label.item()))
plt.imshow(img) # numpy格式才可以用matplotlib
plt.axis('off')
二、构建简单的CNN网络
对于一般的CNN网络来说,都是由特征提取网络和分类网络构成,其中特征提取网络用于提取图片的特征,分类网络用于将图片进行分类。
⭐1. torch.nn.Conv2d() 详解
函数原型:
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1,groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)
关键参数说明:
● in_channels ( int ) – 输入图像中的通道数
● out_channels ( int ) – 卷积产生的通道数
● kernel_size ( int or tuple ) – 卷积核的大小
● stride ( int or tuple , optional ) – 卷积的步幅。默认值:1
● padding ( int , tuple或str , optional ) – 添加到输入的所有四个边的填充。默认值:0
● padding_mode (字符串,可选) – ‘zeros’,‘reflect’,‘replicate’或’circular’。 默认:‘zeros’
⭐2. torch.nn.Linear()详解
函数原型:
In [10]
torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)
关键参数说明:
● in_features:每个输入样本的大小
● out_features:每个输出样本的大小
⭐3. torch.nn.MaxPool2d()详解
函数原型:
torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False,ceil_mode=False)
关键参数说明:
● kernel_size:最大的窗口大小
● stride:窗口的步幅,默认值为 kernel_size
● padding:填充值,默认为0
● dilation:控制窗口中元素步幅的参数
大家注意一下在卷积层和全连接层之间,我们可以使用之前是 torch.flatten() 也可以使用我下面的 x.view() 亦或是 torch.nn.Flatten() 。
torch.nn.Flatten() 与TensorFlow中的 Flatten()层类似,前两者则仅仅是一种数据集拉伸操作(将二维数据拉伸为一维)。
torch.flatten() 方法不会改变x本身,而是返回一个新的张量。
而 x.view() 方法则是直接在原有数据上进行操作。
In [11]
class Net(nn.Module):
def __init__(self):
super(Net, 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(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
model = Net().to(device)
model
三、训练模型
1.设置超参数
In [12]
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learning_rate = 1e-4 # 学习率
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
2.编写训练函数
optimizer.zero_grad()
函数会遍历模型的所有参数,通过内置方法截断反向传播的梯度流,再将每个参数的梯度值设为0,即上一次的梯度记录被清空。
loss.backward()
PyTorch的反向传播(即 tensor.backward() )是通过autograd包来实现的,autograd包会根据tensor进行过的数学运算来自动计算其对应的梯度。
具体来说,torch.tensor是autograd包的基础类,如果你设置tensor的requires_grads为True,就会开始跟踪这个tensor上面的所有运算,如果你做完运算后使用 tensor.backward() ,所有的梯度就会自动运算,tensor的梯度将会累加到它的.grad属性里面去。
更具体地说,损失函数loss是由模型的所有权重w经过一系列运算得到的,若某个w的requires_grads为True,则w的所有上层参数(后面层的权重w)的.grad_fn属性中就保存了对应的运算,然后在使用 loss.backward() 后,会一层层的反向传播计算每个w的梯度值,并保存到该w的.grad属性中。
如果没有进行 tensor.backward() 的话,梯度值将会是None,因此 loss.backward() 要写在 optimizer.step() 之前。
optimizer.step()
step()函数的作用是执行一次优化步骤,通过梯度下降法来更新参数的值。因为梯度下降是基于梯度的,所以在执行 optimizer.step() 函数前应先执行 loss.backward() 函数来计算梯度。
注意:optimizer只负责通过梯度下降进行优化,而不负责产生梯度,梯度是 tensor.backward() 方法产生的。
In [13]
def train(model, trainloader):
train_accuracy, train_loss = 0, 0
train_size = len(trainloader.dataset)
iteration = train_size / batch_size
model.train()
for x, y in trainloader:
if torch.cuda.is_available():
x, y = x.to(device), y.to(device)
pred = model(x)
loss = loss_fn(pred, y)
optimizer.zero_grad
loss.backward()
optimizer.step()
with torch.no_grad():
pred = torch.argmax(pred, dim=1)
train_accuracy += (pred == y).sum().item()
train_loss += loss.item()
train_accuracy /= train_size
train_loss /= iteration
return train_accuracy, train_loss
3. 编写测试函数
测试函数和训练函数大致相同,但是由于不进行梯度下降对网络权重进行更新,所以不需要传入优化器
In [14]
def test(model, testloader):
test_accuracy, test_loss = 0, 0
test_size = len(testloader.dataset)
iteration = test_size / batch_size
model.eval()
with torch.no_grad():
for x, y in testloader:
if torch.cuda.is_available():
x, y = x.to(device), y.to(device)
pred = model(x)
loss = loss_fn(pred, y)
pred = torch.argmax(pred, dim=1)
test_accuracy += (pred == y).sum().item()
test_loss += loss.item()
test_accuracy /= test_size
test_loss /= iteration
return test_accuracy, test_loss
4. 正式训练
model.train()
model.train() 的作用是启用 Batch Normalization 和 Dropout。
如果模型中有 BN 层(Batch Normalization)和 Dropout ,需要在训练时添加 model.train() 。model.train() 是保证BN层能够用到每一批数据的均值和方差。
对于 Dropout ,model.train() 是随机取一部分网络连接来训练更新参数。
model.eval()
model.eval() 的作用是不启用 Batch Normalization 和 Dropout。
如果模型中有BN层(Batch Normalization)和Dropout,在测试时添加 model.eval() 。
model.eval() 是保证BN层能够用全部训练数据的均值和方差,即测试过程中要保证BN层的均值和方差不变。
对于 Dropout , model.eval() 是利用到了所有网络连接,即不进行随机舍弃神经元。
训练完train样本后,生成的模型model要用来测试样本。在 model(test) 之前,需要加上 model.eval() ,否则的话,有输入数据,即使不训练,它也会改变权值。这是model中含有BN层和Dropout所带来的的性质。
In [15]
epochs = 50
train_loss = []
train_acc = []
test_loss = []
test_acc = []
for epoch in range(epochs):
epoch_train_acc, epoch_train_loss = train(model, train_dl)
epoch_test_acc, epoch_test_loss = test(model, test_dl)
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_accuracy:{:.1f}%, Train_loss:{:.3f}, Test_accuracy:{:.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')
四、结果可视化
In [16]
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()