目录

Szegedy C, Liu W, Jia Y, et al. Going deeper with convolutions[C]. computer vision and pattern recognition, 2015: 1-9.

@article{szegedy2015going,

title={Going deeper with convolutions},

author={Szegedy, Christian and Liu, Wei and Jia, Yangqing and Sermanet, Pierre and Reed, Scott and Anguelov, Dragomir and Erhan, Dumitru and Vanhoucke, Vincent and Rabinovich, Andrew},

pages={1--9},

year={2015}}

这里讲的很细, 不多赘诉了.

代码

"""
代码虽然是"copy"源代码, 但是收获不少.
虽然参数少, 但是训练得很慢, 是因为要传三次梯度?
测试集上正确率维0.8682
""" import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import numpy as np
import os class BasicConv2d(nn.Module): def __init__(self, in_channels, out_channels, **kwargs):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels,
bias=False, **kwargs) #不要偏置
#eps 为了数值稳定 默认是1e-5
self.bn = nn.BatchNorm2d(out_channels, eps=0.001)
self.relu = nn.ReLU(inplace=True) def forward(self, x):
x = self.conv(x)
x = self.bn(x)
out = self.relu(x)
return out class Inception(nn.Module): def __init__(self, in_channels, ch1x1, ch3x3red, ch3x3,
ch5x5red, ch5x5, pool_proj):
"""
:param in_channels: 输入的通道数
:param ch1x1: 1x1卷积核的输出通道数
:param ch3x3red: 3x3一开始的1x1部分的通道数
:param ch3x3: 3x3后半的3x3部分的通道数
:param ch5x5: ...
:param ch5x5red: ...
:param pool_proj: 池化层的通道数
"""
super(Inception, self).__init__() self.branch1 = BasicConv2d(in_channels, ch1x1, kernel_size=1) self.branch2 = nn.Sequential(
BasicConv2d(in_channels, ch3x3red, kernel_size=1),
BasicConv2d(ch3x3red, ch3x3, kernel_size=3, padding=1)
) #pytorch 这里用的3x3卷积核?
self.branch3 = nn.Sequential(
BasicConv2d(in_channels, ch5x5red, kernel_size=1),
BasicConv2d(ch5x5red, ch5x5, kernel_size=5, padding=2)
) self.branch4 = nn.Sequential(
nn.MaxPool2d(kernel_size=3, stride=1, padding=1, ceil_mode=True),
BasicConv2d(in_channels, pool_proj, kernel_size=1)
) def forward(self, x):
x1 = self.branch1(x)
x2 = self.branch2(x)
x3 = self.branch3(x)
x4 = self.branch4(x)
out = (x1, x2, x3, x4)
return torch.cat(out, 1) class InceptionAux(nn.Module): def __init__(self, in_channels, num_classes):
super(InceptionAux, self).__init__()
self.avgpool = nn.AdaptiveAvgPool2d((4, 4))
self.conv = BasicConv2d(in_channels, 128, kernel_size=1)
#N x 128 x 4 x 4
self.dense = nn.Sequential(
nn.Linear(2048, 1024),
nn.ReLU(inplace=True),
nn.Dropout(0.7),
nn.Linear(1024, num_classes)
) def forward(self, x):
x = self.avgpool(x)
x = self.conv(x)
x = torch.flatten(x, 1)
out = self.dense(x)
return out class GoogLeNet(nn.Module): def __init__(self, num_classes=10, aux_logits=True):
"""
:param num_classes: 类别个数
:param aux_logits: 是否需要添加辅助训练器
"""
super(GoogLeNet, self).__init__()
self.aux_logits =aux_logits # N x 3 x 224 x 224
self.conv1 = BasicConv2d(3, 64, kernel_size=7, stride=2, padding=3)
# N x 64 x 112 x 112
self.maxpool1 = nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)
# N x 64 x 56 x 56
self.conv2 = BasicConv2d(64, 64, kernel_size=1)
self.conv3 = BasicConv2d(64, 192, kernel_size=3, padding=1)
# N x 192 x 56 x 56
self.maxpool2 = nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)
# N x 192 x 28 x 28 self.inception3a = Inception(192, 64, 96, 128, 16, 32, 32)
#N x 256 x 28 x 28
self.inception3b = Inception(256, 128, 128, 192, 32, 96, 64)
#N x 480 x 28 x 28
self.maxpool3 = nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)
#N x 480 x 14 x 14 self.inception4a = Inception(480, 192, 96, 208, 16, 48, 64)
#N x 512 x 14 x 14
self.inception4b = Inception(512, 160, 112, 224, 24, 64, 64)
#N x 512 x 14 x 14
self.inception4c = Inception(512, 128, 128, 256, 24, 64, 64)
#N x 512 x 14 x 14
self.inception4d = Inception(512, 112, 144, 288, 32, 64, 64)
#N x 528 x 14 x 14
self.inception4e = Inception(528, 256, 160, 320, 32, 128, 128)
#N x 832 x 14 x 14
self.maxpool4 = nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)
#N x 832 x 7 x 7 self.inception5a = Inception(832, 256, 160, 320, 32, 128, 128)
#N x 832 x 7 x 7
self.inception5b = Inception(832, 384, 192, 384, 48, 128, 128)
#N x 1024 x 7 x 7
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
#N x 1024 x 1 x 1
self.drop = nn.Dropout(0.4)
self.fc = nn.Linear(1024, num_classes) if self.aux_logits:
self.aux1 = InceptionAux(512, num_classes)
self.aux2 = InceptionAux(528, num_classes) 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.aux_logits and self.training:
aux1 = self.aux1(x)
x = self.inception4b(x)
x = self.inception4c(x)
x = self.inception4d(x)
if self.aux_logits and self.training:
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.drop(x)
out = self.fc(x) if self.aux_logits and self.training:
return (out, aux1, aux2)
return out class Train: def __init__(self, lr=0.01, momentum=0.9, weight_decay=0.0001):
self.net = GoogLeNet()
self.criterion = nn.CrossEntropyLoss()
self.opti = torch.optim.SGD(self.net.parameters(),
lr=lr, momentum=momentum,
weight_decay=weight_decay)
self.gpu()
self.generate_path()
self.acc_rates = []
self.errors = [] def gpu(self):
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
if torch.cuda.device_count() > 1:
print("Let'us use %d GPUs" % torch.cuda.device_count())
self.net = nn.DataParallel(self.net)
self.net = self.net.to(self.device) def generate_path(self):
"""
生成保存数据的路径
:return:
"""
try:
os.makedirs('./paras')
os.makedirs('./logs')
os.makedirs('./infos')
except FileExistsError as e:
pass
name = self.net.__class__.__name__
paras = os.listdir('./paras')
logs = os.listdir('./logs')
infos = os.listdir('./infos')
number = max((len(paras), len(logs), len(infos)))
self.para_path = "./paras/{0}{1}.pt".format(
name,
number
) self.log_path = "./logs/{0}{1}.txt".format(
name,
number
)
self.info_path = "./infos/{0}{1}.npy".format(
name,
number
) def log(self, strings):
"""
运行日志
:param strings:
:return:
"""
# a 往后添加内容
with open(self.log_path, 'a', encoding='utf8') as f:
f.write(strings) def save(self):
"""
保存网络参数
:return:
"""
torch.save(self.net.state_dict(), self.para_path) def derease_lr(self, multi=0.96):
"""
降低学习率
:param multi:
:return:
"""
self.opti.param_groups[0]['lr'] *= multi def train(self, trainloder, epochs=50):
data_size = len(trainloder) * trainloder.batch_size
part = int(trainloder.batch_size / 2)
for epoch in range(epochs):
running_loss = 0.
total_loss = 0.
acc_count = 0.
if (epoch + 1) % 8 is 0:
self.derease_lr()
self.log(#日志记录
"learning rate change!!!\n"
)
for i, data in enumerate(trainloder):
imgs, labels = data
imgs = imgs.to(self.device)
labels = labels.to(self.device)
(out, aux1, aux2) = self.net(imgs)
loss1 = self.criterion(out, labels)
loss2 = self.criterion(aux1, labels)
loss3 = self.criterion(aux2, labels)
loss = 0.4 * loss1 + 0.3 * loss2 + 0.3 * loss3
_, pre = torch.max(out, 1) #判断是否判断正确
acc_count += (pre == labels).sum().item() #加总对的个数 self.opti.zero_grad()
loss.backward()
self.opti.step() running_loss += loss.item() if (i+1) % part is 0:
strings = "epoch {0:<3} part {1:<5} loss: {2:<.7f}\n".format(
epoch, i, running_loss / part
)
self.log(strings)#日志记录
total_loss += running_loss
running_loss = 0.
self.acc_rates.append(acc_count / data_size)
self.errors.append(total_loss / data_size)
self.log( #日志记录
"Accuracy of the network on %d train images: %d %%\n" %(
data_size, acc_count / data_size * 100
)
)
self.save() #保存网络参数
#保存一些信息画图用
np.save(self.info_path, {
'acc_rates': np.array(self.acc_rates),
'errors': np.array(self.errors)
}) if __name__ == "__main__": root = "../../data" trainset = torchvision.datasets.CIFAR10(root=root, train=True,
download=False,
transform=transforms.Compose(
[transforms.Resize(224),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
)) train_loader = torch.utils.data.DataLoader(trainset, batch_size=128,
shuffle=True, num_workers=8,
pin_memory=True) dog = Train()
dog.train(train_loader, epochs=1000)

Going Deeper with Convolutions (GoogLeNet)的更多相关文章

  1. 【CV论文阅读】Going deeper with convolutions(GoogLeNet)

    目的: 提升深度神经网络的性能. 一般方法带来的问题: 增加网络的深度与宽度. 带来两个问题: (1)参数增加,数据不足的情况容易导致过拟合 (2)计算资源要求高,而且在训练过程中会使得很多参数趋向于 ...

  2. Going deeper with convolutions(GoogLeNet、Inception)

    从LeNet-5开始,cnn就有了标准的结构:stacked convolutional layers are followed by one or more fully-connected laye ...

  3. 解读(GoogLeNet)Going deeper with convolutions

    (GoogLeNet)Going deeper with convolutions Inception结构 目前最直接提升DNN效果的方法是increasing their size,这里的size包 ...

  4. 图像分类(一)GoogLenet Inception_V1:Going deeper with convolutions

    论文地址 在该论文中作者提出了一种被称为Inception Network的深度卷积神经网络,它由若干个Inception modules堆叠而成.Inception的主要特点是它能提高网络中计算资源 ...

  5. Going deeper with convolutions 这篇论文

    致网友:如果你不小心检索到了这篇文章,请不要看,因为很烂.写下来用于作为我的笔记. 2014年,在LSVRC14(large-Scale Visual Recognition Challenge)中, ...

  6. Going Deeper with Convolutions阅读摘要

      论文链接:Going deeper with convolutions 代码下载: Abstract We propose a deep convolutional neural network ...

  7. [论文阅读]Going deeper with convolutions(GoogLeNet)

    本文采用的GoogLenet网络(代号Inception)在2014年ImageNet大规模视觉识别挑战赛取得了最好的结果,该网络总共22层. Motivation and High Level Co ...

  8. 【网络结构】GoogLeNet inception-v1:Going deeper with convolutions论文笔记

    目录 0. 论文链接 1. 概述 2. inception 3. GoogleNet 参考链接 @ 0. 论文链接 1. 概述   GoogLeNet是谷歌团队提出的一种大体保持计算资源不变的前提下, ...

  9. 论文阅读笔记四十二:Going deeper with convolutions (Inception V1 CVPR2014 )

    论文原址:https://arxiv.org/pdf/1409.4842.pdf 代码连接:https://github.com/titu1994/Inception-v4(包含v1,v2,v4)   ...

随机推荐

  1. C/C++ Qt 数据库与ComBox多级联动

    Qt中的SQL数据库组件可以与ComBox组件形成多级联动效果,在日常开发中多级联动效果应用非常广泛,例如当我们选择指定用户时,我们让其在另一个ComBox组件中列举出该用户所维护的主机列表,又或者当 ...

  2. fastJson序列化

    在pojo实体中有map<String,Object>的属性,有个key是user它存储在数据库中是用户的id数组,而在aop里会对这个属性做用户详细信息查询并重新put给user.在做J ...

  3. ORACLE 服务器验证

    位于$ORACLE_HOME/network/admin/sqlnet.oraSQLNET.AUTHENTICATION_SERVICES=none|all|ntsnone:关闭操作系统认证,只能密码 ...

  4. 一份不错的Java就业指导

    想要成为合格的Java程序员或工程师到底需要具备哪些专业技能,面试者在面试之前到底需要准备哪些东西呢? 本文陈列的这些内容既可以作为个人简历中的内容,也可以作为面试的时候跟面试官聊的东西,你可以把这些 ...

  5. Oracle 表结构管理

    表其实是数据的'容器'.oracle有几种类型的表: 普通表(ordinary table)又叫堆组织表. 聚簇表(clustered table) 分区表(partition table) 外部表( ...

  6. 【Java】【IDE】【Jetbrain Idea】Intellij IDEA 快捷键整理

    [常规] Ctrl+Shift + Enter,语句完成 "!",否定完成,输入表达式时按 "!"键 Ctrl+E,最近的文件 Ctrl+Shift+E,最近更 ...

  7. SSM框架整合后使用pagehelper实现分页功能

    一.导入pagehelper-5.1.10.jar和jsqlparser-3.1.jar两个jar包 二.配置pagehelper 2.1 在mybatis配置文件中配置 <plugins> ...

  8. 如何优雅正确地通过interrupt方法中断线程

    为什么废弃Thread的stop函数? 简单来说就是stop方法中断线程太过暴力随意,且会是否线程持有的锁,会导致线程安全问题.还有可能导致存在需要被释放的资源得不到释放,引发内存泄露.所以用stop ...

  9. frp实现基于反向代理的内网穿透

    个人博客主页: xzajyjs.cn frp是什么 简单地说,frp就是一个反向代理软件,它体积轻量但功能很强大,可以使处于内网或防火墙后的设备对外界提供服务,它支持HTTP.TCP.UDP等众多协议 ...

  10. 《手把手教你》系列技巧篇(五十一)-java+ selenium自动化测试-字符串操作-下篇(详解教程)

    1.简介 自动化测试中进行断言的时候,我们可能经常遇到的场景.从一个字符串中找出一组数字或者其中的某些关键字,而不是将这一串字符串作为结果进行断言.这个时候就需要我们对字符串进行操作,宏哥这里介绍两种 ...