深度学习中的数据增强与实现

1. 数据增强Data Augmentation

  • 数据增强让有限的数据产生更多的数据,增加训练样本的数量以及多样性(噪声数据),提升模型鲁棒性。神经网络需要大量的参数,许许多多的神经网路的参数都是数以百万计,而使得这些参数可以正确工作则需要大量的数据进行训练,但在很多实际的项目中,我们难以找到充足的数据来完成任务。
  • 随机改变训练样本可以降低模型对某些属性的依赖,从而提高模型的泛化能力
    1. 例如,我们可以对图像进行不同方式的裁剪,让物体以不同的实例出现在图像的不同位置,这同样能够降低模型对目标位置的敏感性。
    2. 例如,我们也可以调整亮度、对比度、饱和度和色调 等因素来降低模型对 色彩的敏感度。

2. 数据增强的分类

数据增强可以分为两类,一类是离线增强,一类是在线增强。

  1. 离线增强 : 直接对数据集进行处理,数据的数目会变成增强因子乘以原数据集的数目,这种方法常常用于数据集很小的时候。

  2. 在线增强 : 这种增强的方法用于,获得 batch 数据之后,然后对这个 batch 的数据进行增强,如旋转、平移、翻折等相应的变化,由于有些数据集不能接受线性级别的增长,这种方法长用于大的数据集,很多机器学习框架已经支持了这种数据增强方式,并且可以使用 GPU 优化计算。

3. 数据增强实现

数据增强一般是图像用的多,都是一些常用的方法,比如random crop,随机反转,随机对比度增强,颜色变化等等,一般来讲随机反转和一个小比例的random resize,再接random crop比较常用。NLP中将字和词连接起来就形成了一个新样本,也属于数据增强。

图片数据增强通常只是针对训练数据,对于测试数据则用得较少。

3.1 PIL 实现

# -*- coding:utf-8 -*-
"""数据增强
   1. 翻转变换 flip
   2. 随机修剪 random crop
   3. 色彩抖动 color jittering
   4. 平移变换 shift
   5. 尺度变换 scale
   6. 对比度变换 contrast
   7. 噪声扰动 noise
   8. 旋转变换/反射变换 Rotation/reflection
   author: XiJun.Gong
   date:2016-11-29
"""

from PIL import Image, ImageEnhance, ImageOps, ImageFile
import numpy as np
import random
import threading, os, time
import logging

logger = logging.getLogger(__name__)
ImageFile.LOAD_TRUNCATED_IMAGES = True


class DataAugmentation:
    """
    包含数据增强的八种方式
    """


    def __init__(self):
        pass

    @staticmethod
    def openImage(image):
        return Image.open(image, mode="r")

    @staticmethod
    def randomRotation(image, mode=Image.BICUBIC):
        """
         对图像进行随机任意角度(0~360度)旋转
        :param mode 邻近插值,双线性插值,双三次B样条插值(default)
        :param image PIL的图像image
        :return: 旋转转之后的图像
        """
        random_angle = np.random.randint(1, 360)
        return image.rotate(random_angle, mode)

    @staticmethod
    def randomCrop(image):
        """
        对图像随意剪切,考虑到图像大小范围(68,68),使用一个一个大于(36*36)的窗口进行截图
        :param image: PIL的图像image
        :return: 剪切之后的图像

        """
        image_width = image.size[0]
        image_height = image.size[1]
        crop_win_size = np.random.randint(40, 68)
        random_region = (
            (image_width - crop_win_size) >> 1, (image_height - crop_win_size) >> 1, (image_width + crop_win_size) >> 1,
            (image_height + crop_win_size) >> 1)
        return image.crop(random_region)

    @staticmethod
    def randomColor(image):
        """
        对图像进行颜色抖动
        :param image: PIL的图像image
        :return: 有颜色色差的图像image
        """
        random_factor = np.random.randint(0, 31) / 10.  # 随机因子
        color_image = ImageEnhance.Color(image).enhance(random_factor)  # 调整图像的饱和度
        random_factor = np.random.randint(10, 21) / 10.  # 随机因子
        brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor)  # 调整图像的亮度
        random_factor = np.random.randint(10, 21) / 10.  # 随机因1子
        contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor)  # 调整图像对比度
        random_factor = np.random.randint(0, 31) / 10.  # 随机因子
        return ImageEnhance.Sharpness(contrast_image).enhance(random_factor)  # 调整图像锐度

    @staticmethod
    def randomGaussian(image, mean=0.2, sigma=0.3):
        """
         对图像进行高斯噪声处理
        :param image:
        :return:
        """

        def gaussianNoisy(im, mean=0.2, sigma=0.3):
            """
            对图像做高斯噪音处理
            :param im: 单通道图像
            :param mean: 偏移量
            :param sigma: 标准差
            :return:
            """
            for _i in range(len(im)):
                im[_i] += random.gauss(mean, sigma)
            return im

        # 将图像转化成数组
        img = np.asarray(image)
        img.flags.writeable = True  # 将数组改为读写模式
        width, height = img.shape[:2]
        img_r = gaussianNoisy(img[:, :, 0].flatten(), mean, sigma)
        img_g = gaussianNoisy(img[:, :, 1].flatten(), mean, sigma)
        img_b = gaussianNoisy(img[:, :, 2].flatten(), mean, sigma)
        img[:, :, 0] = img_r.reshape([width, height])
        img[:, :, 1] = img_g.reshape([width, height])
        img[:, :, 2] = img_b.reshape([width, height])
        return Image.fromarray(np.uint8(img))

    @staticmethod
    def saveImage(image, path):
        image.save(path)


def makeDir(path):
    try:
        if not os.path.exists(path):
            if not os.path.isfile(path):
                # os.mkdir(path)
                os.makedirs(path)
            return 0
        else:
            return 1
    except Exception, e:
        print str(e)
        return -2


def imageOps(func_name, image, des_path, file_name, times=5):
    funcMap = {"randomRotation": DataAugmentation.randomRotation,
               "randomCrop": DataAugmentation.randomCrop,
               "randomColor": DataAugmentation.randomColor,
               "randomGaussian": DataAugmentation.randomGaussian
               }
    if funcMap.get(func_name) is None:
        logger.error("%s is not exist", func_name)
        return -1

    for _i in range(0, times, 1):
        new_image = funcMap[func_name](image)
        DataAugmentation.saveImage(new_image, os.path.join(des_path, func_name + str(_i) + file_name))


opsList = {"randomRotation", "randomCrop", "randomColor", "randomGaussian"}


def threadOPS(path, new_path):
    """
    多线程处理事务
    :param src_path: 资源文件
    :param des_path: 目的地文件
    :return:
    """
    if os.path.isdir(path):
        img_names = os.listdir(path)
    else:
        img_names = [path]
    for img_name in img_names:
        print img_name
        tmp_img_name = os.path.join(path, img_name)
        if os.path.isdir(tmp_img_name):
            if makeDir(os.path.join(new_path, img_name)) != -1:
                threadOPS(tmp_img_name, os.path.join(new_path, img_name))
            else:
                print 'create new dir failure'
                return -1
                # os.removedirs(tmp_img_name)
        elif tmp_img_name.split('.')[1] != "DS_Store":
            # 读取文件并进行操作
            image = DataAugmentation.openImage(tmp_img_name)
            threadImage = [0] * 5
            _index = 0
            for ops_name in opsList:
                threadImage[_index] = threading.Thread(target=imageOps,
                                                       args=(ops_name, image, new_path, img_name,))
                threadImage[_index].start()
                _index += 1
                time.sleep(0.2)


if __name__ == '__main__':
    threadOPS("/home/pic-image/train/12306train",
              "/home/pic-image/train/12306train3")

3.2 TensorFlow 实现

#encoding:utf-8
'''
tf 参考链接 :https://tensorflow.google.cn/api_guides/python/image
增加数据量,减轻过拟合,增强模型的泛化能力
在预测时也可以使用
'''
import numpy as np
import os
import math
import tensorflow as tf
from skimage import io
import random
import matplotlib.pyplot as plt
 
def read_image(image_path):
    image_raw_data = tf.gfile.FastGFile(image_path,'rb').read()
    image_data = tf.image.decode_png(image_raw_data)
    return image_data
 
'''
    #图像大小的调整,放大缩小
    不同尺寸
    tf.image.resize_images(img,size,size,method), 0,默认 双线性插值;1,最近邻算法;
                                              2, 双3次插值法;3,面积插值法
'''
def resize_image(image_data):
    
    res = []
    image_biliner = tf.image.resize_images(image_data,[256,256],method=0)   
 
    image_nn = tf.image.resize_images(image_data,[256,256],method=1)
    image_bicubic = tf.image.resize_images(image_data,[256,256],method=2)
    image_area = tf.image.resize_images(image_data,[256,256],method=3)
 
    res.append(tf.to_int32(image_biliner))
    res.append(tf.to_int32(image_nn))
    res.append(tf.to_int32(image_bicubic))
    res.append(tf.to_int32(image_area))
    
    return res
 
'''
#裁剪
识别不同位置的物体
'''
def crop_image(image_data):
    res = []
    #在中间位置进行裁剪或者周围填充0
    image_crop = tf.image.resize_image_with_crop_or_pad(image_data,256,256) 
    image_pad = tf.image.resize_image_with_crop_or_pad(image_data,512,512)
    
    #按照比列 裁剪图像的中心区域
    image_center_crop = tf.image.central_crop(image_data,0.5)
 
    #随机裁剪(常用方法)
    image_random_crop0 = tf.random_crop(image_data,[300,300,3])
    image_random_crop1 = tf.random_crop(image_data,[300,300,3])
 
    res.append(tf.to_int32(image_crop))
    res.append(tf.to_int32(image_pad))
    res.append(tf.to_int32(image_center_crop))
    res.append(tf.to_int32(image_random_crop0)) 
    res.append(tf.to_int32(image_random_crop1))
 
    return res
 
'''
    #旋转(镜像)
    图像旋转不会影响识别的结果,可以在多个角度进行旋转,使模型可以识别不同角度的物体
    当旋转或平移的角度较小时,可以通过maxpooling来保证旋转和平移的不变性。
'''
def flip_image(image_data):
 
    #镜像
    res = []
    #上下翻转
    image_up_down_flip = tf.image.flip_up_down(image_data)
 
    #左右翻转
    image_left_right_filp = tf.image.flip_left_right(image_data)
 
    #对角线旋转
    image_transpose = tf.image.transpose_image(image_data)
 
    #旋转90度 
    image_rot1 = tf.image.rot90(image_data,1)
    image_rot2 = tf.image.rot90(image_data,2)
    image_rot3 = tf.image.rot90(image_data,3)
 
    res.append(tf.to_int32(image_up_down_flip))
    res.append(tf.to_int32(image_left_right_filp))
    res.append(tf.to_int32(image_transpose))
    res.append(tf.to_int32(image_rot1))
    res.append(tf.to_int32(image_rot2))
    res.append(tf.to_int32(image_rot3))
 
    return res
 
#图像色彩调整
'''
    根据原始数据模拟出更多的不同场景下的图像
    brightness(亮度),适应不同光照下的物体
    constrast(对比度), hue(色彩), saturation(饱和度) 
    可自定义和随机
'''
def color_image(image_data):
    res = []
 
    image_random_brightness = tf.image.random_brightness(image_data,0.5)
    image_random_constrast = tf.image.random_contrast(image_data,0,1)
    image_random_hue = tf.image.random_hue(image_data,0.5)
    image_random_saturation = tf.image.random_saturation(image_data,0,1)
 
    #颜色空间变换
    images_data = tf.to_float(image_data)
    image_hsv_rgb = tf.image.rgb_to_hsv(images_data)
    # image_gray_rgb = tf.image.rgb_to_grayscale(image_data)
    # image_gray_rgb = tf.expand_dims(image_data[2],1)
 
    res.append(tf.to_int32(image_random_brightness))
    res.append(tf.to_int32(image_random_constrast))
    res.append(tf.to_int32(image_random_hue))
    res.append(tf.to_int32(image_random_saturation))
    res.append(tf.to_int32(image_hsv_rgb))
    return res
 
#添加噪声
def PCA_Jittering(img):
 
    img_size = img.size/3
    print(img.size,img_size)
    img1= img.reshape(int(img_size),3)
    img1 = np.transpose(img1)
    img_cov = np.cov([img1[0], img1[1], img1[2]])  
    #计算矩阵特征向量
    lamda, p = np.linalg.eig(img_cov)
 
    p = np.transpose(p)  
    #生成正态分布的随机数
    alpha1 = random.normalvariate(0,0.2)  
    alpha2 = random.normalvariate(0,0.2)  
    alpha3 = random.normalvariate(0,0.2)  
 
    v = np.transpose((alpha1*lamda[0], alpha2*lamda[1], alpha3*lamda[2])) #加入扰动  
    add_num = np.dot(p,v)  
 
    img2 = np.array([img[:,:,0]+add_num[0], img[:,:,1]+add_num[1], img[:,:,2]+add_num[2]])  
 
    img2 = np.swapaxes(img2,0,2)  
    img2 = np.swapaxes(img2,0,1)  
 
    return img2
 
def main(_):
    image_path = 'dog.png'
    image_data = read_image(image_path)
    img = tf.image.per_image_standardization(image_data)
    resize = resize_image(image_data)
    crop = crop_image(image_data)
    flip = flip_image(image_data)
    color = color_image(image_data)
    init = tf.global_variables_initializer()
 
    with tf.Session() as sess:
        sess.run(init)
        img, resize_res, crop_res, flip_res, color_res = sess.run([img,
            resize,crop,flip,color])
        
        res = []
        res.append(resize_res)
        res.append(crop_res)
        res.append(flip_res)
        res.append(color_res)
 
        for cat in res:
            fig = plt.figure()
            num = 1
            for i in cat:   
                x = math.ceil(len(cat)/2) #向上取整             
                fig.add_subplot(2,x,num)    
                plt.imshow(i)
                num = num+1
            plt.show()
        img = PCA_Jittering(img)
        plt.imshow(img)
        plt.show()
if __name__ == '__main__':
    tf.app.run()

3.3 Keras 实现

#!/usr/bin/env python
#-*- coding: utf-8 -*-

# import packages
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

datagen = ImageDataGenerator(
        rotation_range=0.2,
        width_shift_range=0.2,
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True,
        fill_mode='nearest')

img = load_img('~/Desktop/lena.jpg')  # this is a PIL image, please replace to your own file path
x = img_to_array(img)  # this is a Numpy array with shape (3, 150, 150)
x = x.reshape((1,) + x.shape)  # this is a Numpy array with shape (1, 3, 150, 150)

# the .flow() command below generates batches of randomly transformed images
# and saves the results to the `preview/` directory

i = 0
for batch in datagen.flow(x, 
                          batch_size=1,
                          save_to_dir='~/Desktop/preview',  
                          save_prefix='lena', 
                          save_format='jpg'):
    i += 1
    if i > 20:
        break  # otherwise the generator would loop indefinitely

3.4 Pytorch实现

import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision.datasets import CIFAR10
from utils import train, resnet
from torchvision import transforms as tfs
# 使用数据增强
def train_tf(x):
    im_aug = tfs.Compose([
        tfs.Resize(120),
        tfs.RandomHorizontalFlip(),
        tfs.RandomCrop(96),
        tfs.ColorJitter(brightness=0.5, contrast=0.5, hue=0.5),
        tfs.ToTensor(),
        tfs.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
    ])
    x = im_aug(x)
    return x

def test_tf(x):
    im_aug = tfs.Compose([
        tfs.Resize(96),
        tfs.ToTensor(),
        tfs.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
    ])
    x = im_aug(x)
    return x

train_set = CIFAR10('./data', train=True, transform=train_tf)
train_data = torch.utils.data.DataLoader(train_set, batch_size=64, shuffle=True)
test_set = CIFAR10('./data', train=False, transform=test_tf)
test_data = torch.utils.data.DataLoader(test_set, batch_size=128, shuffle=False)

net = resnet(3, 10)
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()
train(net, train_data, test_data, 10, optimizer, criterion)

3.5 imgaug 图像增强库实现

更加去参考:https://github.com/aleju/imgaug

4. 总结

数据增强主要对训练数据进行操作的一种正则化技术。顾名思义,数据增强通过应用一系列方法随机地改变训练数据,比如平移,旋转,剪切和翻转等。数据增强的详细变换幅度需要根据具体的应用数据而设计,只要注意一点:应用这些简单的转换不能改变输入图像的标签。每个通过增强得到的图像都可以被认为是一个“新”图像。这样我们可以不断的给模型提供新的训练样本,使模型能够学习到更加具有辨别力,更具泛化性的特征。

应用数据增强技术可以提高模型的准确率,同时有助于减轻过拟合。此外,数据增强也可以增加数据量,降低深度学习需要的人工标记的大量数据集。尽管收集“自然”的训练样本越多越好,但是在无法增加真实的训练样本时,数据增强可以用来克服小数据集的局限性。

5. 参考

深度学习与计算机视觉(PB-02)-数据增强

深度学习中的数据增强(data augmentation)

Keras ImageDataGenerator使用

深度学习入门之Pytorch——数据增强

图像增强库Image augmentation for machine learning experiments

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270