文章目录
1、常见的数据扩增方法
MixUp
介绍
(参考https://blog.csdn.net/sinat_36618660/article/details/101633504)
mixup是一种运用在计算机视觉中的对图像进行混类增强的算法,它可以将不同类之间的图像进行混合,从而扩充训练数据集。
原理
假设
b
a
t
c
h
x
1
batch_{x1}
batchx1是一个
b
a
t
c
h
batch
batch样本,
b
a
t
c
h
y
1
batch_{y1}
batchy1是该样本对应的标签;
b
a
t
c
h
x
2
batch_{x2}
batchx2是另一个
b
a
t
c
h
batch
batch样本,
b
a
t
c
h
y
2
batch_{y2}
batchy2是该样本对应的标签,
λ
\lambda
λ是由参数为
α
\alpha
α,
β
\beta
β的贝塔分布计算出来的混合系数,
由此我们可以得到mixup原理公式为:
$ {\lambda=Beta(\alpha,\beta)\tag{3.1}}$
KaTeX parse error: \tag works only in display equations
KaTeX parse error: \tag works only in display equations
其中 B e t a B e t a BetaBeta BetaBeta指的是贝塔分布, m i x e d _ b a t c h x mixed\_batch_{x} mixed_batchx是混合后的batch样本, m i x e d _ b a t c h y mixed\_batch_{y} mixed_batchy是混合后的batch样本对应的标签。
在本baseline中的代码如下:
缺点
就是无法保证合成的图片的语义信息.比如在样本空间中扩充一个样本点,这个样本点所处的位置在该任务中可能本来就没什么意义,这样的话这个新生成的样本是无效的.当然,通过调节Mixup中的beta分布的参数(上图公式中的alpha),可以降低了发生这种情况的概率,但过于保险的alpha值又可能发挥不出Mixup的优点.
def mixup_data(x, y, alpha=1.0, use_cuda=True):
'''Returns mixed inputs, pairs of targets, and lambda'''
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
batch_size = x.size()[0]
if use_cuda:
index = torch.randperm(batch_size).cuda()
else:
index = torch.randperm(batch_size)
mixed_x = lam * x + (1 - lam) * x[index, :]
y_a, y_b = y, y[index]
return mixed_x, y_a, y_b, lam
def mixup_criterion(criterion, pred, y_a, y_b, lam):
return lam * criterion(pred, y_a.view(-1, 1)) + (1 - lam) * criterion(pred, y_b.view(-1, 1))
AugMix
介绍
AugMix的总体操作流程并不算复杂,作者主要将它分为三个部分,即增强,融合,损失函数,具体的流程论文里有一个清晰的伪代码:
缺点时间复杂度高。
缺点
时间复杂度高
Cutout
介绍
随机的将样本中的部分区域cut掉,并且填充0像素值,分类的结果不变;
CutMix
介绍
就是将一部分区域cut掉但不填充0像素而是随机填充训练集中的其他数据的区域像素值,分类结果按一定的比例分配
2、 加入几种数据扩增完成训练
由于目前已经使用上了Mixup进行数据扩增可以尝试一下使用其他的方法,比如Cutmix,代码如下:
"""输入为:样本的size和生成的随机lamda值"""
def rand_bbox(size, lam):
W = size[2]
H = size[3]
"""1.论文里的公式2,求出B的rw,rh"""
cut_rat = np.sqrt(1. - lam)
cut_w = np.int(W * cut_rat)
cut_h = np.int(H * cut_rat)
# uniform
"""2.论文里的公式2,求出B的rx,ry(bbox的中心点)"""
cx = np.random.randint(W)
cy = np.random.randint(H)
#限制坐标区域不超过样本大小
bbx1 = np.clip(cx - cut_w // 2, 0, W)
bby1 = np.clip(cy - cut_h // 2, 0, H)
bbx2 = np.clip(cx + cut_w // 2, 0, W)
bby2 = np.clip(cy + cut_h // 2, 0, H)
"""3.返回剪裁B区域的坐标值"""
return bbx1, bby1, bbx2, bby2
for i, (input, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
input = input.cuda()
target = target.cuda()
r = np.random.rand(1)
if args.beta > 0 and r < args.cutmix_prob:
# generate mixed sample
"""1.设定lamda的值,服从beta分布"""
lam = np.random.beta(args.beta, args.beta)
"""2.找到两个随机样本"""
rand_index = torch.randperm(input.size()[0]).cuda()
target_a = target#一个batch
target_b = target[rand_index] #将原有batch打乱顺序
"""3.生成剪裁区域B"""
bbx1, bby1, bbx2, bby2 = rand_bbox(input.size(), lam)
"""4.将原有的样本A中的B区域,替换成样本B中的B区域"""
#打乱顺序后的batch组和原有的batch组进行替换[对应id下]
input[:, :, bbx1:bbx2, bby1:bby2] = input[rand_index, :, bbx1:bbx2, bby1:bby2]
# adjust lambda to exactly match pixel ratio
"""5.根据剪裁区域坐标框的值调整lam的值"""
lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (input.size()[-1] * input.size()[-2]))
# compute output
"""6.将生成的新的训练样本丢到模型中进行训练"""
output = model(input)
"""7.按lamda值分配权重"""
loss = criterion(output, target_a) * lam + criterion(output, target_b) * (1. - lam)
else:
# compute output
output = model(input)
loss = criterion(output, target)
3、学习率改变方法
当学习率设置的过小时,收敛过程将变得十分缓慢。而当学习率设置的过大时,梯度可能会在最小值附近来回震荡,甚至可能无法收敛。
PyTorch学习率调整策略通过torch.optim.lr_scheduler接口实现。PyTorch提供的学习率调整策略分为三大类,分别是
- 有序调整:等间隔调整(Step),按需调整学习率(MultiStep),指数衰减调整(Exponential)和 余弦退火CosineAnnealing。
- 自适应调整:自适应调整学习率 ReduceLROnPlateau。
- 自定义调整:自定义调整学习率 LambdaLR
1 等间隔调整学习率 StepLR
等间隔调整学习率,调整倍数为 gamma 倍,调整间隔为 step_size。间隔单位是step。需要注意的是, step 通常是指 epoch,不要弄成 iteration 了。
# step_size(int)- 学习率下降间隔数,若为 30,则会在 30、 60、 90…个 step 时,将学习率调整为 lr*gamma。
# gamma(float)- 学习率调整倍数,默认为 0.1 倍,即下降 10 倍。
# last_epoch(int)- 上一个 epoch 数,这个变量用来指示学习率是否需要调整。当last_epoch 符合设定的间隔时,就会对学习率进行调整。当为-1 时,学习率设置为初始值。
torch.optim.lr_scheduler.StepLR(optimizer, step_size, gamma=0.1, last_epoch=-1)
2 按需调整学习率 MultiStepLR
按设定的间隔调整学习率。这个方法适合后期调试使用,观察 loss 曲线,为每个实验定制学习率调整时机。
# milestones(list)- 一个 list,每一个元素代表何时调整学习率, list 元素必须是递增的。如 milestones=[30,80,120]
# gamma(float)- 学习率调整倍数,默认为 0.1 倍,即下降 10 倍。
torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones, gamma=0.1, last_epoch=-1)
3 指数衰减调整学习率 ExponentialLR
按指数衰减调整学习率
# gamma- 学习率调整倍数的底,指数为 epoch,即 gamma**epoch
torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma, last_epoch=-1)
4 余弦退火调整学习率 CosineAnnealingLR
以余弦函数为周期,并在每个周期最大值时重新设置学习率。以初始学习率为最大学习率,以 2 ∗ T m a x 2*Tmax2∗Tmax 为周期,在一个周期内先下降,后上升。
torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max, eta_min=0, last_epoch=-1)
5 自适应调整学习率 ReduceLROnPlateau
当某指标不再变化(下降或升高),调整学习率,这是非常实用的学习率调整策略。
例如,当验证集的 loss 不再下降时,进行学习率调整;或者监测验证集的 accuracy,当accuracy 不再上升时,则调整学习率。
# mode(str)- 模式选择,有 min 和 max 两种模式, min 表示当指标不再降低(如监测loss), max 表示当指标不再升高(如监测 accuracy)。
# factor(float)- 学习率调整倍数(等同于其它方法的 gamma),即学习率更新为 lr = lr * factor
# patience(int)- 忍受该指标多少个 step 不变化,当忍无可忍时,调整学习率。
#verbose(bool)- 是否打印学习率信息, print(‘Epoch {:5d}: reducing learning rate of group {} to {:.4e}.’.format(epoch, i, new_lr))
#threshold_mode(str)- 选择判断指标是否达最优的模式,有两种模式, rel 和 abs。
#threshold(float)- 配合 threshold_mode 使用。
#cooldown(int)- “冷却时间“,当调整学习率之后,让学习率调整策略冷静一下,让模型再训练一段时间,再重启监测模式。
#min_lr(float or list)- 学习率下限,可为 float,或者 list,当有多个参数组时,可用 list 进行设置。
#eps(float)- 学习率衰减的最小值,当学习率变化小于 eps 时,则不调整学习率。
torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=10, verbose=False, threshold=0.0001, threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-08)
6 自定义调整学习率 LambdaLR
为不同参数组设定不同学习率调整策略。调整规则为,
l
r
=
b
a
s
e
_
l
r
∗
l
m
b
d
a
(
s
e
l
f
.
l
a
s
t
_
e
p
o
c
h
)
lr=base\_lr∗lmbda(self.last\_epoch)
lr=base_lr∗lmbda(self.last_epoch)
fine-tune 中十分有用,我们不仅可为不同的层设定不同的学习率,还可以为其设定不同的学习率调整策略。
# lr_lambda(function or list)- 一个计算学习率调整倍数的函数,输入通常为 step,当有多个参数组时,设为 list。
torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda, last_epoch=-1)