深度学习5

网络结构

img

  • 引入Inception结构,融合不同尺度的特征信息
  • 使用1x1的卷积核进行降维以及映射处理
  • 添加两个辅助分类器帮助训练
  • 丢弃全连接层,使用平均池化层,大大减少模型参在这里插入图片描述

Inception结构

image-20220521144254867

以往卷积层采用串行结构,输入一次只通过一层得到一个输出。Inception结构将输入并行通过几个层,然后将堆叠成最终的输出。

(因为最后将输出堆叠成在一起,相当于增加通道数,因此输出的特征矩阵的大小必须一致才能进行堆叠)

  • 使用1x1卷积核,减少输入的维度,在通过大卷积核,从而大大减少了参数个数。

网络搭建

根据GoogLeNet的网络结构我们可以看出,其网络结构非常复杂,因此在搭建网络时与之前的网络搭建略有不同。

BasicConv2d

1
2
3
4
5
6
7
8
9
10
class BasicConv2d(nn.Module):
def __init__(self,in_channels,out_channels,**kwargs):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels,out_channels=out_channels,**kwargs)
self.relu = nn.ReLU(inplace=True)

def forward(self,x):
x = self.conv(x)
x = self.relu(x)
return x

在GoogLeNet中卷积层后采用ReLU激活函数,卷积层BasicConvd类封装了一个基本的卷积单元结构,包括一个卷积层+一个ReLU激活函数,方便简化后续代码。

Inception

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Inception(nn.Module):
def __init__(self, in_channels, conv1x1, conv3x3_reduce, conv3x3, conv5x5_reduce, conv5x5, maxpooling_reduce):
self.banch1 = BasicConv2d(in_channels=in_channels, out_channels=conv1x1, kernel_size=1)
self.banch2 = nn.Sequential(
BasicConv2d(in_channels=in_channels, out_channels=conv3x3_reduce, kernel_size=1),
BasicConv2d(in_channels=in_channels, out_channels=conv3x3, kernel_size=3, padding=1)
)
self.banch3 = nn.Sequential(
BasicConv2d(in_channels=in_channels, out_channels=conv5x5_reduce, kernel_size=1),
BasicConv2d(in_channels=in_channels, out_channels=conv5x5, kernel_size=5, padding=2)
)
self.banch4 = nn.Sequential(
nn.MaxPool2d(kernel_size=3, padding=1, stride=1),
BasicConv2d(in_channels=in_channels, out_channels=maxpooling_reduce, kernel_size=1)
)

def forward(self, x):
x1 = self.banch1(x)
x2 = self.banch2(x)
x3 = self.banch3(x)
x4 = self.banch4(x)
return torch.cat([x1, x2, x3, x4], 1) # 将四个分支输出按照channels维度拼接

Inception类定义了Inception结构,正向传播过程中输入分别通过四个分支后使用torch.cat函数将输出按照channels叠加在一起。需要注意的是,在卷积过程中采用same填充方式保证各个分支的输出特征图的宽和高相同,否则无法拼接。

Auxiliary

GoogLeNet有两个辅助分类器帮助训练,使用Auxiliary类封装辅助分类器结构。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Auxiliary(nn.Module):
def __init__(self,in_channels,num_classes):
super(Auxiliary, self).__init__()
self.avagepooling = nn.AvgPool2d(kernel_size=5,stride=3)
self.conv = BasicConv2d(in_channels=in_channels,out_channels=128, kernel_size=1)
self.fc1 = nn.Linear(2048,1024)
self.fc2 = nn.Linear(1024,num_classes)

def forward(self,x):
x = self.avagepooling(x)
x = self.conv(x)
x = torch.flatten(x,1)
x = dropout(x,0.5,self.training)

x = self.fc1(x)
x = relu(x,inplace=True)
x = dropout(x,0.5,self.training)

x = self.fc2(x)
return x

GoogLeNet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class GoogLeNet(nn.Module):
def __init__(self, num_classes, auxiliary = True, init_weights = False):
super(GoogLeNet, self).__init__()
self.aux_logits = auxiliary

self.conv1 = BasicConv2d(3, 64, kernel_size=7, stride=2, padding=3)
self.maxpool1 = nn.MaxPool2d(3, stride=2, ceil_mode=True)

self.conv2 = BasicConv2d(64, 64, kernel_size=1)
self.conv3 = BasicConv2d(64, 192, kernel_size=3, padding=1)
self.maxpool2 = nn.MaxPool2d(3, stride=2, ceil_mode=True)

self.inception3a = Inception(192, 64, 96, 128, 16, 32, 32)
self.inception3b = Inception(256, 128, 128, 192, 32, 96, 64)
self.maxpool3 = nn.MaxPool2d(3, stride=2, ceil_mode=True)

self.inception4a = Inception(480, 192, 96, 208, 16, 48, 64)
self.inception4b = Inception(512, 160, 112, 224, 24, 64, 64)
self.inception4c = Inception(512, 128, 128, 256, 24, 64, 64)
self.inception4d = Inception(512, 112, 144, 288, 32, 64, 64)
self.inception4e = Inception(528, 256, 160, 320, 32, 128, 128)
self.maxpool4 = nn.MaxPool2d(3, stride=2, ceil_mode=True)

self.inception5a = Inception(832, 256, 160, 320, 32, 128, 128)
self.inception5b = Inception(832, 384, 192, 384, 48, 128, 128)

if self.aux_logits:
self.aux1 = Auxiliary(512, num_classes)
self.aux2 = Auxiliary(528, num_classes)

self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.dropout = nn.Dropout(0.4)
self.fc = nn.Linear(1024, num_classes)
if init_weights:
self._initialize_weights()

def forward(self, x):
x = self.conv1(x)
x = self.maxpool1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.maxpool2(x)

x = self.inception3a(x)
x = self.inception3b(x)
x = self.maxpool3(x)
x = self.inception4a(x)
if self.training and self.aux_logits:
aux1 = self.aux1(x)

x = self.inception4b(x)
x = self.inception4c(x)
x = self.inception4d(x)
if self.training and self.aux_logits:
aux2 = self.aux2(x)

x = self.inception4e(x)
x = self.maxpool4(x)
x = self.inception5a(x)
x = self.inception5b(x)

x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.dropout(x)
x = self.fc(x)
if self.training and self.aux_logits:
return x, aux2, aux1
return x

def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)

训练

GoogLeNet的训练过程与之前类似,不同的是网络有辅助分类器,在训练时会计算出三个loss,最后按照1、0.3、0.3的权重相加进行反向传播。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
BATCH_SIZE = 16
EPOCH = 10
DEVICE = 'cuda:0' if torch.cuda.is_available() else 'cpu'

data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
]),
'val': transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
}
train_data = datasets.ImageFolder('./dataset/train',transform=data_transforms['train'])
val_data = datasets.ImageFolder('./dataset/val',transform=data_transforms['val'])

classes = train_data.classes

train_dataset = DataLoader(train_data,
batch_size=BATCH_SIZE,
shuffle=True,
num_workers=0)
validate_dataset = DataLoader(val_data,
batch_size=BATCH_SIZE,
shuffle=False,
num_workers=0)

net = GoogLeNet(num_classes=5,auxiliary=True).to(DEVICE)
loss_func = nn.CrossEntropyLoss()
optimizer = optim.Adam(params=net.parameters(),lr= 0.0001)

best_acc = 0.0
for epoch in range(EPOCH):
net.train()
train_loss = 0.0
for step,data in enumerate(train_dataset):
images,labels = data
optimizer.zero_grad()
logits, aux_logits2, aux_logits1 = net(images.to(DEVICE))
loss0 = loss_func(logits, labels.to(DEVICE))
loss1 = loss_func(aux_logits1, labels.to(DEVICE))
loss2 = loss_func(aux_logits2, labels.to(DEVICE))
loss = loss0 + loss1 * 0.3 + loss2 * 0.3
loss.backward()
optimizer.step()

train_loss += loss.item()

rate = (step+1)/len(train_dataset)
a = '▉' * int( rate * 100)
b = ' ' * int( (1-rate) * 100)

print("\rtrain loss: {:^3.0f}%[{}->{}]{:.3f}".format(int(rate * 100),a,b,loss),end="")
print()
net.eval()
acc = 0.0
with torch.no_grad():
for date_test in validate_dataset:
test_images,test_labels = date_test
outputs = net(test_images.to(DEVICE))
predict_y = torch.max(outputs, dim=1)[1]
acc += (predict_y == test_labels.to(DEVICE)).sum().item()
val_acc = acc / len(validate_dataset)
if val_acc > best_acc:
best_acc = val_acc
torch.save(net.state_dict(),'./models/model.pth')
print('[epoch %d] train_loss: %.3f val_accuracy: %.3f' %
(epoch + 1, train_loss / len(train_dataset), val_acc))
print('Finished Training')

笔记根据B站UP主霹雳吧啦Wz视频合集【深度学习-图像分类篇章】学习整理