欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

模型训练技巧——Random Erasing

程序员文章站 2022-03-11 19:21:05
...

论文:https://arxiv.org/pdf/1708.04896v2.pdf

代码:https://github.com/zhunzhong07/Random-Erasing

1. 论文核心

 

模型训练技巧——Random Erasing
Caption

          训练模型时,随机选取一个图片的矩形区域,将这个矩形区域的像素值用随机值或者平均像素值代替,产生局部遮挡的效果。该数据增强可以与随机切除、随机翻转等数据增强结合起来使用。

2. 代码实现

      代码中:

      Sl、Sh分别是需要随机擦除的矩形面积大小上下阈值;

      r1是限制矩形长宽比r的阈值 ;

import random
import math
import cv2
import numpy as np

class RandomErasing:
    """Random erasing the an rectangle region in Image.
    Class that performs Random Erasing in Random Erasing Data Augmentation by Zhong et al.

    Args:
        sl: min erasing area region 
        sh: max erasing area region
        r1: min aspect ratio range of earsing region
        p: probability of performing random erasing
    """

    def __init__(self, p=0.5, sl=0.02, sh=0.4, r1=0.3):

        self.p = p
        self.s = (sl, sh)
        self.r = (r1, 1/r1)
    

    def __call__(self, img):
        """
        perform random erasing
        Args:
            img: opencv numpy array in form of [w, h, c] range 
                 from [0, 255]
        
        Returns:
            erased img
        """

        assert len(img.shape) == 3, 'image should be a 3 dimension numpy array'

        if random.random() > self.p:
            return img
        
        else:
            while True:
                Se = random.uniform(*self.s) * img.shape[0] * img.shape[1]
                re = random.uniform(*self.r) 

                He = int(round(math.sqrt(Se * re)))
                We = int(round(math.sqrt(Se / re)))

                xe = random.randint(0, img.shape[1])
                ye = random.randint(0, img.shape[0])

                if xe + We <= img.shape[1] and ye + He <= img.shape[0]:
                    img[ye : ye + He, xe : xe + We, :] = np.random.randint(low=0, high=255, size=(He, We, img.shape[2]))

                    return img


if __name__ == "__main__":
    img = cv2.imread("test.jpg")
    RE = RandomErasing(p=1)
    for i in range(20):
        img1 = RE(img.copy())
        cv2.imshow("test", img1)
        cv2.waitKey(1000)  

3. 实验效果

模型训练技巧——Random Erasing
Caption

        从实验可以看出,Random Erasing 可以降低识别的错误率,与Random flipping、Random cropping结合起来用效果更好。

模型训练技巧——Random Erasing
Caption

         从实验可以看出,用上Random erasing可以提高目标检测的map。