0 过拟合与图像增强
通常我们训练一个深度卷积神经网络需要足够多的数据来防止模型过拟合,然而收集任务所需的数据往往代价较大。因此我们需要另辟蹊径,而图像增强就是另一种简单可行的防止过拟合的方法。
本质上,图像增强就是一个从已有的训练样本中创建新的训练样本的过程。要制作一个新样本,可以对原始图像进行轻微的更改。例如,你可以让一个新图像更亮一点;你可以从原始图像上切下一块;你可以通过镜像原来的图像来创建一个新的图像等等。
现在图像增强(包含在广义的数据增强中)已经成为深度学习训练过程的标配,下面介绍今天的主角:又快又强的图像增强库——albumentations
1 安装
pip install albumentations
2 使用
给出一个简单的使用示例:
import albumentations as A
transform = A.Compose([
A.RandomCrop(width=256, height=256),
A.HorizontalFlip(p=0.5),
A.RandomBrightnessContrast(p=0.2),
])
image = cv2.imread("/path/to/image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
transformed_image = transform(image=image)["image"]
注意图像需要先转化成numpy数组,针对opencv还需要将BGR格式转化为RGB格式。
数据增强需要同时对图像和标签进行相同的操作,考虑到不同任务的标签不同,有以下几种使用对象:
- 图像
- Mask. 针对分割任务。
- BBox. 针对检测任务。
- Keypoints.
这里有各种变换及其支持的操作对象列表:
https://albumentations.ai/docs/getting_started/transforms_and_targets/
3 常用操作
这个库支持的操作太多了,这里列出我个人常用的且实验确实有效的:
- HorizontalFlip
- VerticalFlip
- Transpose
- RandomResizeCrop
- Rotate
- PadIfNeeded
训练时目标的大小(scale)很影响模型的泛化性能,增加scale上的数据增强有一定作用。
这里的目标大小指的是:模型输入的图像目标相对于卷积核的大小,影响因素有输入图像尺寸及目标相对图像尺寸的大小。