携手创造,一起成长!这是我参与「日新计划 8 月更文应战」的第5天,点击检查活动详情
摘要
本文经过对植物幼苗分类的实践例子来感触一下超大核的魅力地点。这篇文章能让你学到:
-
经过对论文的解读,了解RepLKNet超大核的规划思想和架构。
-
怎么运用数据增强,包含transforms的增强、CutOut、MixUp、CutMix等增强手段?
-
怎么调用自定义的模型?
-
怎么运用混合精度练习?
-
怎么运用梯度裁剪防止梯度爆破?
-
怎么运用DP多显卡练习?
-
怎么绘制loss和acc曲线?
-
怎么生成val的测评报告?
-
怎么编写测验脚本测验测验集?
-
怎么运用余弦退火战略调整学习率?
论文解读
pytoch代码:github.com/DingXiaoH/R…
论文翻译:wanghao.blog.csdn.net/article/det…
RepLKNet的作者受vision transformers (ViT) 最新进展的启发,提出了3131的超大核模型,与小核 CNN 相比,大核 CNN 具有更大的有用感触野和更高的形状误差而不是纹路误差。学习 Swin Transformer 的微观架构,提出了一种架构 RepLKNet。在 ImageNet 上获得 87.8% 的 top-1 准确率,在 ADE20K 上获得 56.0% mIoU,这在具有相似模型大小的最先进技术中十分具有竞争力。
论文的奉献
论文的首要奉献有:
-
总结了运用超大核的五条原则:
-
基于以上原则,简略学习 Swin Transformer 的微观架构,咱们提出了一种架构 RepLKNet,其中很多运用超大卷积,如 27×27、31×31 等。这一架构的其他部分十分简略,都是 1×1 卷积、Batch Norm 等脍炙人口的简略结构,不用任何 attention。
-
基于超大卷积核,对有用感触野、shape bias(模型做决议的时分到底是看物体的形状还是看部分的纹路?)、Transformers 之所以功能强悍的原因等话题的讨论和分析。咱们发现,ResNet-152 等传统深层小 kernel 模型的有用感触野其实不大,大 kernel 模型不光有用感触野更大而且更像人类(shape bias 高),Transformer 可能要害在于大 kernel 而不在于 self-attention 的详细方法。
应战传统认知
RepLKNet的呈现,打破了我们对CNN的固有的认知,首要有:
-
超大卷积不光不涨点,而且还掉点?RepLKNet证明,超大卷积在曩昔没人用,不代表其现在不能用。在现代 CNN 规划(shortcut、重参数化等)的加持下,kernel size 越大越涨点!
-
超大卷积功率很差?超大 depth-wise 卷积并不会增加多少 FLOPs。假如再加点底层优化,速度会更快,31×31 的核算密度最高可达 3×3 的 70 倍!
-
大卷积只能用在大 feature map 上?作者发现,在 7×7 的 feature map 上用 13×13 卷积都能涨点。
-
ImageNet 点数阐明一切?咱们发现,下流(方针检测、语义分割等)任务的功能可能跟 ImageNet 关系不大。
-
超深 CNN(如 ResNet-152)堆叠很多 3×3,所以感触野很大?作者发现,深层小 kernel 模型有用感触野其实很小。反而少量超大卷积核的有用感触野十分大。
-
Transformers(ViT、Swin 等)在下流任务上功能强悍,是因为 self-attention(Query-Key-Value 的规划方法)实质更强?作者用超大卷积核验证,发现kernel size 可能才是下流涨点的要害。
整体架构
作者也说了,架构就是用了Swin Transformer ,首要在于把 attention 换成超大卷积和与之配套的结构,再加一点 CNN 风格的改动。依据以上五条原则,RepLKNet 的规划元素包含 shortcut、depth-wise 超大 kernel、小 kernel 重参数化等。整体架构如下:
下面咱们经过对植物幼苗分类的实践例子来感触一下超大核的魅力地点。
装置包
1、装置timm
运用pip就行,指令:
pip install timm
2、装置apex
下载apex库,链接: github.com/NVIDIA/apex…
cd C:\Users\XX\Downloads\apex-master #进入apex目录
pip install -r requirements.txt
依赖装置完后,翻开cmd,cd进入到刚刚下载完的apex-master路径下,运转:
python setup.py install
数据增强Cutout和Mixup
为了进步成果我在代码中加入Cutout和Mixup这两种增强方法。实现这两种增强需求装置torchtoolbox。装置指令:
pip install torchtoolbox
Cutout实现,在transforms中。
from torchtoolbox.transform import Cutout
# 数据预处理
transform = transforms.Compose([
transforms.Resize((224, 224)),
Cutout(),
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
需求导入包:from timm.data.mixup import Mixup,
定义Mixup,和SoftTargetCrossEntropy
mixup_fn = Mixup(
mixup_alpha=0.8, cutmix_alpha=1.0, cutmix_minmax=None,
prob=0.1, switch_prob=0.5, mode='batch',
label_smoothing=0.1, num_classes=12)
criterion_train = SoftTargetCrossEntropy()
参数详解:
mixup_alpha (float): mixup alpha 值,假如 > 0,则 mixup 处于活动状况。
cutmix_alpha (float):cutmix alpha 值,假如 > 0,cutmix 处于活动状况。
cutmix_minmax (List[float]):cutmix 最小/最大图画比率,cutmix 处于活动状况,假如不是 None,则运用这个 vs alpha。
假如设置了 cutmix_minmax 则cutmix_alpha 默以为1.0
prob (float): 每批次或元素使用 mixup 或 cutmix 的概率。
switch_prob (float): 当两者都处于活动状况时切换cutmix 和mixup 的概率 。
mode (str): 怎么使用 mixup/cutmix 参数(每个’batch’,’pair’(元素对),’elem’(元素)。
correct_lam (bool): 当 cutmix bbox 被图画边框取舍时使用。 lambda 校正
label_smoothing (float):将标签滑润使用于混合方针张量。
num_classes (int): 方针的类数。
项目结构
RepLKNet_demo
├─data
│ ├─Black-grass
│ ├─Charlock
│ ├─Cleavers
│ ├─Common Chickweed
│ ├─Common wheat
│ ├─Fat Hen
│ ├─Loose Silky-bent
│ ├─Maize
│ ├─Scentless Mayweed
│ ├─Shepherds Purse
│ ├─Small-flowered Cranesbill
│ └─Sugar beet
├─models
│ ├─__init__.py
│ └─replknet.py
├─RepLKNet-31B_ImageNet-1K_224.pth
├─mean_std.py
├─makedata.py
├─train.py
└─test.py
mean_std.py:核算mean和std的值。
makedata.py:生成数据集。
replknet.py:来自官方的pytorch版别的代码。
RepLKNet-31B_ImageNet-1K_224.pth:预练习权重。 下载链接:download.csdn.net/download/hh… 运用官方的replknet.py有个位置报错,这是对DW卷积的优化,假如环境有问题,装置不上这个包,可以不采用DepthWiseConv2dImplicitGEMM卷积。
核算mean和std
为了使模型更加快速的收敛,咱们需求核算出mean和std的值,新建mean_std.py,插入代码:
from torchvision.datasets import ImageFolder
import torch
from torchvision import transforms
def get_mean_and_std(train_data):
train_loader = torch.utils.data.DataLoader(
train_data, batch_size=1, shuffle=False, num_workers=0,
pin_memory=True)
mean = torch.zeros(3)
std = torch.zeros(3)
for X, _ in train_loader:
for d in range(3):
mean[d] += X[:, d, :, :].mean()
std[d] += X[:, d, :, :].std()
mean.div_(len(train_data))
std.div_(len(train_data))
return list(mean.numpy()), list(std.numpy())
if __name__ == '__main__':
train_dataset = ImageFolder(root=r'data1', transform=transforms.ToTensor())
print(get_mean_and_std(train_dataset))
数据集结构:
运转结果:
([0.3281186, 0.28937867, 0.20702125], [0.09407319, 0.09732835, 0.106712654])
把这个结果记录下来,后边要用!
生成数据集
咱们收拾还的图画分类的数据集结构是这样的
data
├─Black-grass
├─Charlock
├─Cleavers
├─Common Chickweed
├─Common wheat
├─Fat Hen
├─Loose Silky-bent
├─Maize
├─Scentless Mayweed
├─Shepherds Purse
├─Small-flowered Cranesbill
└─Sugar beet
pytorch和keras默许加载方法是ImageNet数据集格局,格局是
├─data
│ ├─val
│ │ ├─Black-grass
│ │ ├─Charlock
│ │ ├─Cleavers
│ │ ├─Common Chickweed
│ │ ├─Common wheat
│ │ ├─Fat Hen
│ │ ├─Loose Silky-bent
│ │ ├─Maize
│ │ ├─Scentless Mayweed
│ │ ├─Shepherds Purse
│ │ ├─Small-flowered Cranesbill
│ │ └─Sugar beet
│ └─train
│ ├─Black-grass
│ ├─Charlock
│ ├─Cleavers
│ ├─Common Chickweed
│ ├─Common wheat
│ ├─Fat Hen
│ ├─Loose Silky-bent
│ ├─Maize
│ ├─Scentless Mayweed
│ ├─Shepherds Purse
│ ├─Small-flowered Cranesbill
│ └─Sugar beet
新增格局转化脚本makedata.py,插入代码:
import glob
import os
import shutil
image_list=glob.glob('data1/*/*.png')
print(image_list)
file_dir='data'
if os.path.exists(file_dir):
print('true')
#os.rmdir(file_dir)
shutil.rmtree(file_dir)#删去再建立
os.makedirs(file_dir)
else:
os.makedirs(file_dir)
from sklearn.model_selection import train_test_split
trainval_files, val_files = train_test_split(image_list, test_size=0.3, random_state=42)
train_dir='train'
val_dir='val'
train_root=os.path.join(file_dir,train_dir)
val_root=os.path.join(file_dir,val_dir)
for file in trainval_files:
file_class=file.replace("\\","/").split('/')[-2]
file_name=file.replace("\\","/").split('/')[-1]
file_class=os.path.join(train_root,file_class)
if not os.path.isdir(file_class):
os.makedirs(file_class)
shutil.copy(file, file_class + '/' + file_name)
for file in val_files:
file_class=file.replace("\\","/").split('/')[-2]
file_name=file.replace("\\","/").split('/')[-1]
file_class=os.path.join(val_root,file_class)
if not os.path.isdir(file_class):
os.makedirs(file_class)
shutil.copy(file, file_class + '/' + file_name)
完成上面的内容就可以开启练习和测验了,详见下面的链接: