-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdiffaugment.py
executable file
·183 lines (158 loc) · 6.58 KB
/
diffaugment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
from torchvision import datasets, transforms
from scipy.ndimage.interpolation import rotate as scipyrotate
#The contents of this file are taken from DC/DSA's github repo https://github.com/VICO-UoE/DatasetCondensation
class ParamDiffAug():
def __init__(self):
self.aug_mode = 'S' #'multiple or single'
self.prob_flip = 0.5
self.ratio_scale = 1.2
self.ratio_rotate = 15.0
self.ratio_crop_pad = 0.125
self.ratio_cutout = 0.5 # the size would be 0.5x0.5
self.ratio_noise = 0.05
self.brightness = 1.0
self.saturation = 2.0
self.contrast = 0.5
def set_seed_DiffAug(donger):
return
def DiffAugment(x, strategy='', seed = -1, param = None):
if seed == -1:
param.Siamese = False
else:
param.Siamese = True
param.latestseed = seed
if strategy == 'None' or strategy == 'none':
return x
if strategy:
if param.aug_mode == 'M': # original
for p in strategy.split('_'):
for f in AUGMENT_FNS[p]:
x = f(x, param)
elif param.aug_mode == 'S':
pbties = strategy.split('_')
set_seed_DiffAug(param)
p = pbties[torch.randint(0, len(pbties), size=(1,)).item()]
for f in AUGMENT_FNS[p]:
x = f(x, param)
else:
exit('unknown augmentation mode: %s'%param.aug_mode)
x = x.contiguous()
return x
# We implement the following differentiable augmentation strategies based on the code provided in https://github.com/mit-han-lab/data-efficient-gans.
def rand_scale(x, param):
# x>1, max scale
# sx, sy: (0, +oo), 1: orignial size, 0.5: enlarge 2 times
ratio = param.ratio_scale
set_seed_DiffAug(param)
sx = torch.rand(x.shape[0]) * (ratio - 1.0/ratio) + 1.0/ratio
set_seed_DiffAug(param)
sy = torch.rand(x.shape[0]) * (ratio - 1.0/ratio) + 1.0/ratio
theta = [[[sx[i], 0, 0],
[0, sy[i], 0],] for i in range(x.shape[0])]
theta = torch.tensor(theta, dtype=torch.float)
if param.Siamese: # Siamese augmentation:
theta[:] = theta[0]
grid = F.affine_grid(theta, x.shape).to(x.device)
x = F.grid_sample(x, grid)
return x
def rand_rotate(x, param): # [-180, 180], 90: anticlockwise 90 degree
ratio = param.ratio_rotate
set_seed_DiffAug(param)
theta = (torch.rand(x.shape[0]) - 0.5) * 2 * ratio / 180 * float(np.pi)
theta = [[[torch.cos(theta[i]), torch.sin(-theta[i]), 0],
[torch.sin(theta[i]), torch.cos(theta[i]), 0],] for i in range(x.shape[0])]
theta = torch.tensor(theta, dtype=torch.float)
if param.Siamese: # Siamese augmentation:
theta[:] = theta[0]
grid = F.affine_grid(theta, x.shape).to(x.device)
x = F.grid_sample(x, grid)
return x
def rand_flip(x, param):
prob = param.prob_flip
set_seed_DiffAug(param)
randf = torch.rand(x.size(0), 1, 1, 1, device=x.device)
if param.Siamese: # Siamese augmentation:
randf[:] = randf[0]
return torch.where(randf < prob, x.flip(3), x)
def rand_brightness(x, param):
ratio = param.brightness
set_seed_DiffAug(param)
randb = torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device)
if param.Siamese: # Siamese augmentation:
randb[:] = randb[0]
x = x + (randb - 0.5)*ratio
return x
def rand_saturation(x, param):
ratio = param.saturation
x_mean = x.mean(dim=1, keepdim=True)
set_seed_DiffAug(param)
rands = torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device)
if param.Siamese: # Siamese augmentation:
rands[:] = rands[0]
x = (x - x_mean) * (rands * ratio) + x_mean
return x
def rand_contrast(x, param):
ratio = param.contrast
x_mean = x.mean(dim=[1, 2, 3], keepdim=True)
set_seed_DiffAug(param)
randc = torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device)
if param.Siamese: # Siamese augmentation:
randc[:] = randc[0]
x = (x - x_mean) * (randc + ratio) + x_mean
return x
def rand_crop(x, param):
# The image is padded on its surrounding and then cropped.
ratio = param.ratio_crop_pad
shift_x, shift_y = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
set_seed_DiffAug(param)
translation_x = torch.randint(-shift_x, shift_x + 1, size=[x.size(0), 1, 1], device=x.device)
set_seed_DiffAug(param)
translation_y = torch.randint(-shift_y, shift_y + 1, size=[x.size(0), 1, 1], device=x.device)
if param.Siamese: # Siamese augmentation:
translation_x[:] = translation_x[0]
translation_y[:] = translation_y[0]
grid_batch, grid_x, grid_y = torch.meshgrid(
torch.arange(x.size(0), dtype=torch.long, device=x.device),
torch.arange(x.size(2), dtype=torch.long, device=x.device),
torch.arange(x.size(3), dtype=torch.long, device=x.device),
)
grid_x = torch.clamp(grid_x + translation_x + 1, 0, x.size(2) + 1)
grid_y = torch.clamp(grid_y + translation_y + 1, 0, x.size(3) + 1)
x_pad = F.pad(x, [1, 1, 1, 1, 0, 0, 0, 0])
x = x_pad.permute(0, 2, 3, 1).contiguous()[grid_batch, grid_x, grid_y].permute(0, 3, 1, 2)
return x
def rand_cutout(x, param):
ratio = param.ratio_cutout
cutout_size = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5)
set_seed_DiffAug(param)
offset_x = torch.randint(0, x.size(2) + (1 - cutout_size[0] % 2), size=[x.size(0), 1, 1], device=x.device)
set_seed_DiffAug(param)
offset_y = torch.randint(0, x.size(3) + (1 - cutout_size[1] % 2), size=[x.size(0), 1, 1], device=x.device)
if param.Siamese: # Siamese augmentation:
offset_x[:] = offset_x[0]
offset_y[:] = offset_y[0]
grid_batch, grid_x, grid_y = torch.meshgrid(
torch.arange(x.size(0), dtype=torch.long, device=x.device),
torch.arange(cutout_size[0], dtype=torch.long, device=x.device),
torch.arange(cutout_size[1], dtype=torch.long, device=x.device),
)
grid_x = torch.clamp(grid_x + offset_x - cutout_size[0] // 2, min=0, max=x.size(2) - 1)
grid_y = torch.clamp(grid_y + offset_y - cutout_size[1] // 2, min=0, max=x.size(3) - 1)
mask = torch.ones(x.size(0), x.size(2), x.size(3), dtype=x.dtype, device=x.device)
mask[grid_batch, grid_x, grid_y] = 0
x = x * mask.unsqueeze(1)
return x
AUGMENT_FNS = {
'color': [rand_brightness, rand_saturation, rand_contrast],
'crop': [rand_crop],
'cutout': [rand_cutout],
'flip': [rand_flip],
'scale': [rand_scale],
'rotate': [rand_rotate],
}