- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
- 🚀 文章来源:K同学的学习圈子
本次采用的数据集为网络上下载的天气图像数据集,。
本人电脑配置
Python 3.8.17
Pytorch 2.0
torchvision 0.15.2 + cpu
前期准备
1. 设置GPU/CPU
本次是在cpu上对网络进行训练和测试,同样需要先识别设备。
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
2. 导入数据
下载数据到主目录的文件夹的weather_photos文件夹里,文件夹下为4类的子文件夹,每一个文件夹为一类,其中cloudy, rain, shine, sunrise的图片数量分别为300,215,253,357,共1125张图片。图片示例如下
在这里把每张图片resize到224*224,并对数据进行归一化。在划分训练集和测试集时比例为0.8:0.2。在对数据进行封装时依旧采用的是dataloader。
import os, PIL, random, pathlib
data_dir = 'weather_photos/'
data_dir = pathlib.Path(data_dir)
data_paths = list(data_dir.glob('*'))
classNames = [str(path).split("\\")[1] for path in data_paths]
print(classNames)
total_datadir = 'weather_photos/'
train_transforms = transforms.Compose([transforms.Resize([224,224]),
transforms.ToTensor(),
transforms.Normalize(
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)
# split the data
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])
# load data
batch_size = 32
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)
构建网络模型
1. 搭建模型
构建含有四层卷积的卷积神经网络,其中用到了batch normalization的操作,BN层一般位于激活函数前,可以保证激活单元的非线性表达能力,缓解梯度消失问题。
# construct the CNN with batch normalization
class Network_bn(nn.Module):
def __init__(self):
super(Network_bn, 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(classNames))
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
2. 可视化模型
利用torchinfo包查看模型的结构并计算模型每一层的参数量,显示出来的结果如下。
from torchinfo import summary
model = Model().to(device)
summary(model)
=================================================================
Layer (type:depth-idx) Param #
=================================================================
Network_bn --
├─Conv2d: 1-1 912
├─BatchNorm2d: 1-2 24
├─Conv2d: 1-3 3,612
├─BatchNorm2d: 1-4 24
├─MaxPool2d: 1-5 --
├─Conv2d: 1-6 7,224
├─BatchNorm2d: 1-7 48
├─Conv2d: 1-8 14,424
├─BatchNorm2d: 1-9 48
├─Linear: 1-10 240,004
=================================================================
Total params: 266,320
Trainable params: 266,320
Non-trainable params: 0
=================================================================
3. 编写训练函数
设置损失函数,这里采用的交叉熵损失函数,设置优化器为SGD优化,同时在其中加入了动量,也是为了防止过拟合。
# Train the model
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # the size of training set
num_batches = len(dataloader)
train_loss, train_acc = 0, 0
for X, y in dataloader:
X, y = X.to(device), y.to(device)
# calculating the prediction error
pred = model(X)
loss = loss_fn(pred, y)
# backward
optimizer.zero_grad()
loss.backward()
optimizer.step()
# recording the loss and accuracy
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
4. 编写测试函数
当不进行训练时,停止梯度更新,节省计算内存消耗。
# Test the model
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
test_acc, test_loss = 0, 0
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
# calculate 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
5. 主函数
设置迭代epoch次数,这里设定为100,并记录训练误差、精度,测试误差、精度。同时为了保存模型,选取训练过程中测试集上精度最大的模型进行保存。
# Start to train
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')
结果总结
由于图片数量是比较小的,本次训练结果没有那么理想,之后还需要再次查找一下原因。
更新
采用原博主的源代码,我又跑了一遍,发现是没有太大问题的,在20个epoch内,准确率至少可以达到90%,训练得到的误差曲线如下所示
由于没有达到93%, 我增加了网络通道数,使得之前网络的通道数增加一倍,最后输出965050的特征图大小,发现虽然精度有所上升,但训练过程不是太平稳,猜想原因可能是数据集太小导致数据出现过拟合。
呜呜呜,让chatgpt帮我分析了一下代码才发现是我忘记进行损失的回传了!!!这么低级的错误也能出现,下给出修改后的训练结果图,结果与原博主的应该相似。