目录
一、 前期准备
1.1设置GPU和引入环境
1.2导入数据
1.3划分数据集
二、构建简单的CNN网络
三、 训练模型
1. 设置超参数
2. 编写训练函数
3. 编写测试函数
4. 正式训练
四、 结果可视化
五、测试
注:遇到的bug
六、总结
本文为[365天深度学习训练营]中的学习记录博客
参考文章:[Pytorch实战 | 第P3周:彩色图片识别:天气识别]
原作者:[K同学啊|接辅导、项目定制]
难度:新手入门⭐
语言:Python3、Pytorch
要求:
本地读取并加载数据。
测试集accuracy到达93%
拔高:
测试集accuracy到达95%
调用模型识别一张本地图片
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
import os,PIL,pathlib
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
cuda
程序所在文件夹内新建data文件夹,里面放入四个天气的文件数据,最后输出验证一下
data_dir = './data/'
data_dir = pathlib.Path(data_dir)
data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[1] for path in data_paths]
classeNames
['cloudy', 'rain', 'shine', 'sunrise']
进行图形变换,最后输出看一下
torchvision.transforms函数
主要是用于常见的一些图形变换,例如裁剪、旋转等;这里用到
torchvision.transforms.Compose()
类,其主要作用是串联多个图片变换的操作。有兴趣的同学可以参考这篇博客:torchvision.transforms.Compose()详解【Pytorch手册】
total_datadir = './data/'
train_transforms = transforms.Compose([
transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
transforms.Normalize( # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])
total_data = datasets.ImageFolder(total_datadir,transform=train_transforms)
print(total_data)
Dataset ImageFolder
Number of datapoints: 1125
Root location: ./data/
StandardTransform
Transform: Compose(
Resize(size=[224, 224], interpolation=bilinear, max_size=None, antialias=None)
ToTensor()
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
)
设置一下训练集和测试级的大小,和其数据集划分
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)
900 225
设置一下batch_size(想设大但gpu内存好像不够?改了还是那样,利用率低的惊人所以最后设128了以前都是32),用dataloader数据加载一下,记得都要打乱(shuffle=True),并且设num_work=0,即非多进程处理,(为0其实设不设都行我一开始设1但是给改一下default为0因为Linux线程和windows不一样但这个数据集小+我懒所以没改XD)并测试输出(经典操作步骤)
batch_size = 128
train_dl = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=0)
test_dl = torch.utils.data.DataLoader(test_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=0)
# 数据的shape为:[batch_size, channel, height, weight]
# 其中batch_size为自己设定,channel,height和weight分别是图片的通道数,高度和宽度。
for X, y in test_dl:
print("Shape of X [N, C, H, W]: ", X.shape)
print("Shape of y: ", y.shape, y.dtype)
break
Shape of X [N, C, H, W]: torch.Size([32, 3, 224, 224])
Shape of y: torch.Size([32]) torch.int64
CNN网络一般由特征提取网络和分类网络构成,特征提取网络用于提取图片的特征,后者将图片进行分类。
常用的:
torch.nn.Conv2d():
nn.Conv2d为卷积层,用于提取图片的特征,传入参数为输入channel,输出channel,池化核大小
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)是输入的channel数量 第二个参数(out_channels)是输出的channel数量 第三个参数(kernel_size)是卷积核大小 第四个参数(stride)是步长,默认为1 第五个参数(padding)是填充大小,默认为0
torch.nn.Linear():nn.Linear为全连接层,对输入数据应用线性变换。参数(每个输入样本大小,每个输出样本大小)
torch.nn.MaxPool2d():nn.MaxPool2d为池化层,进行下采样,用更高层的抽象表示图像特征,传入参数为池化核大小
最后打印一下相关参数
import torch.nn.functional as F
class Network_bn(nn.Module):
def __init__(self):
super(Network_bn, self).__init__()
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
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
model = Network_bn().to(device)
print(model)
Using cuda device
Network_bn(
(conv1): Conv2d(3, 12, kernel_size=(5, 5), stride=(1, 1))
(bn1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(12, 12, kernel_size=(5, 5), stride=(1, 1))
(bn2): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(conv4): Conv2d(12, 24, kernel_size=(5, 5), stride=(1, 1))
(bn4): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv5): Conv2d(24, 24, kernel_size=(5, 5), stride=(1, 1))
(bn5): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(fc1): Linear(in_features=60000, out_features=4, bias=True)
)
也是在一二周用到的,一模一样
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-4 # 学习率
opt = torch.optim.SGD(model.parameters(),lr=learn_rate)
常用的也还是这三个
1. optimizer.zero_grad()
梯度值grad属性清为0,即上一次梯度记录被清空。
2. loss.backward()
反向传播,会自动计算出对应的梯度,loss.backward()要写在optimizer.step()之前。
3. optimizer.step()
进行优化步骤,通过梯度下降来更新参数的值。写在loss.backward()之后。
训练函数代码很标准:代码部分和week1、2一样。
# 训练循环
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) # 计算网络输出和真实值之间的差距,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
训练函数和测试函数差别不大,但是由于不进行梯度下降对网络权重进行更新,所以不用优化器
(所以测试函数代码部分和week1、2一样)
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, 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
1. model.train()
启动Batch Normalization (BN)和 Dropout。保证前者能够用到每一批数据的均值和方差,对后者将随机取一部分网络连接来训练更新参数。
2. model.eval()
不启用 Batch Normalization 和 Dropout。保证前者能用到所有训练数据集和方差,所以训练过程中BN层的这两个值要保持不变。对后者也是用到所有网络连接,所以要放弃随机舍弃神经元。
训练完train样本后,生成的模型model要用来测试样本。在model(test)之前,需要加上model.eval(),否则的话,有输入数据,即使不训练,它也会改变权值。这是model中含有BN层和Dropout所带来的的性质。
代码又同week1、2:(epochs训练轮数适当增加提高准确率)
epochs = 50
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:42.4%, Train_loss:1.196, Test_acc:50.7%,Test_loss:1.357
Epoch: 2, Train_acc:66.6%, Train_loss:0.925, Test_acc:60.4%,Test_loss:1.271
Epoch: 3, Train_acc:73.9%, Train_loss:0.777, Test_acc:70.7%,Test_loss:1.095
Epoch: 4, Train_acc:77.6%, Train_loss:0.815, Test_acc:68.9%,Test_loss:0.931
Epoch: 5, Train_acc:79.2%, Train_loss:0.698, Test_acc:75.6%,Test_loss:0.783
....一直到50
Done
五十轮后,测试准确率在90%左右
像以前那样,把训练过程弄成统计图,上面参数一样的话代码同week1、2一样
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()
调用本地图片测试
local_test_image = PIL.Image.open ("./p2.png").convert('RGB')
local_transforms = transforms.Compose([
transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
])
local_test_data = local_transforms(local_test_image)
_,result=torch.max(model(local_test_data.to(device).unsqueeze(0)),1)
print(classeNames[result])
提示应该是三通道(RGB),但是是四通道。添加一下(一通道是‘L’)上面代码已经改成RGB了
img = Image.open('test.png')
if img.mode != 'RGB':
img = img.convert('RGB')
结果:
这周不同于week1、2,不是用dataset下载数据集,而是用图片组成的训练集(和我其他博客弄opencv的训练类似),同时最后调用本地图片进行测试。week3比week1、2难一些,通过本篇学习加强了自己对于深度学习的理解。(我在尝试弄模型测试但失败了,成功了再分享)