-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocess.py
317 lines (294 loc) · 9.95 KB
/
preprocess.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""This file contains the code for loading and preprocessing the data.
Note that for the functions to run properly, the appropriate datasets should
already be downloaded to the correct directory:
CIFAR-10: Should be saved to ./datasets/cifar10py/
FMNIST: Should be saved to ./datasets/FMNIST/initial_ds/
synthetic data: Should be saved to ./datasets/synthetic/
"""
import numpy as np
import sys
import pickle as pickle
import time
from skimage import data, color
from skimage.transform import rescale, resize, downscale_local_mean
from scipy.fftpack import dct, idct
from skimage.color import rgb2gray
def unpickle(add):
if '3.6.1' in sys.version:
with open(add, 'rb') as fo:
val = pickle.load(fo, encoding='latin1')
else:
with open(add, 'rb') as fo:
val = pickle.load(fo)
return val
def cifarTrain():
"""This function reads the CIFAR-10 training examples from the disk."""
X = []
Y = []
for i in range(1, 6):
data = unpickle('./datasets/cifar10py/data_batch_%d'%(i))
tempX = data['data']
n = tempX.shape[0]
tempX = tempX.reshape((n, 3, 32, 32))
tempX = tempX.transpose((0, 2, 3, 1))
X.append(tempX)
tempy = np.array(data['labels'])
tempy = tempy.reshape((len(tempy), 1))
Y.append(tempy)
X = np.concatenate(X, axis=0)
Y = np.concatenate(Y, axis=0)
return (Y, X)
def cifarTest():
"""This function reads the CIFAR-10 test examples from the disk."""
data = unpickle('./datasets/cifar10py/test_batch')
tempX = data['data']
n = tempX.shape[0]
tempX = tempX.reshape((n, 3, 32, 32))
tempX = tempX.transpose((0, 2, 3, 1))
tempy = np.array(data['labels'])
tempy = tempy.reshape((len(tempy), 1))
return (tempy, tempX)
def cifar_input(mode, greyscale, CNN):
"""This function preprocesses the CIFAR-10 data.
Inputs:
mode: 'train' or 'test'
greyscale: boolean. If true the images are converted to greyscale.
CNN: boolean. If false, the images are flattened. """
if mode == 'train':
Y, X = cifarTrain()
else:
Y, X = cifarTest()
n = len(Y)
n1 = 32
n2 = 32
nc = 3
if greyscale:
nc = 1
Z = np.zeros((n, n1, n2, nc))
d = n1 * n2 * nc
for i in range(n):
image = X[i]
if greyscale:
image = rgb2gray(image)
image = image - np.mean(image)
image = image / np.linalg.norm(image.flatten()) * np.sqrt(d)
if greyscale:
Z[i, :, :, 0] = image
else:
Z[i] = image
return (Y, Z)
def addHFNoise(X, mfilter, multiplier):
"""This function adds Gaussian noise to frequencies identified by mfilter.
Inputs:
X: A data array of size n x d.
mfilter: A matrix of {0, 1} of size sqrt(d) x sqrt(d).
multiplier: A positive constant corresponding to noise to signal ratio.
Outputs:
Z: A data array of noisy flattened images of size n x d."""
n = X.shape[0]
d = X.shape[1]
n1 = np.int(np.sqrt(d))
Z = np.zeros((n, d))
for i in range(n):
image = X[i, :] + 0.0
image = image - np.mean(image)
image = image.reshape((n1, n1))
freq = dct(dct(image, axis=0, norm='ortho'), axis=1, norm='ortho')
noise = np.random.normal(size=(n1, n1))
noise = np.multiply(noise, mfilter)
noise = noise / np.linalg.norm(noise)
noise = noise * (multiplier * np.linalg.norm(freq))
noisy_freq = freq + noise
newIm = idct(idct(noisy_freq, axis=0, norm='ortho'), axis=1, norm='ortho')
newIm = newIm / np.linalg.norm(newIm)
Z[i, :] = newIm.flatten() * np.sqrt(d)
return Z
def addTHNoise(X, thresh, covHalf, mu):
"""This function adds low-frequency Gaussian noise to greyscale images.
Inputs:
X: A data array of size n x d.
thresh: A frequency threshold (valid range [0, sqrt(d)]).
covHalf: The square root of the noise covariance.
mu: The mean of the noise.
Outputs:
Z: A data array of size n x d containing noise flattened images."""
n = X.shape[0]
d = X.shape[1]
n1 = np.int(np.sqrt(d))
Z = np.zeros((n, d))
noise = np.random.normal(size=(n, d))
noise = np.dot(noise, covHalf) + mu
for i in range(n):
image = X[i].reshape((n1, n1))
image = image - np.mean(image)
image = image / np.linalg.norm(image)
image = image * np.sqrt(d)
freq = dct(dct(image, axis=0, norm='ortho'), axis=1, norm='ortho')
freq[:thresh, :thresh] = noise[i, :].reshape((n1, n1))[:thresh, :thresh]
newIm = idct(idct(freq, axis=0, norm='ortho'), axis=1, norm='ortho')
Z[i, :] = newIm.flatten()
return Z
def addCifarNoise(X, thresh, Shalf, mu):
"""This function adds low frequency noise to the Cifar10 images (As described in Appendix A.6).
Inputs:
X: The data tensor with shape n x 32 x 32 x 3.
thresh: Frequency threshold (valid range: [0, 32]).
Shalf: Square root of the covariance matrix of the noise.
mu: Mean of the noise.
Outputs:
images: A tensor of n x 32 x 32 x 3 of noisy images. """
n = X.shape[0]
n1 = X.shape[1]
c = X.shape[3]
d = n1 * n1 * c
noise = np.random.normal(size=(n, d))
noise = np.dot(noise, Shalf) + mu
Z = np.zeros((n, n1, n1, c))
for i in range(n):
noiseInstance = noise[i, :].reshape((n1, n1, c))
for j in range(c):
image = X[i, :, :, j]
Z[i, :, :, j] = dct(dct(image, axis=0, norm='ortho'), axis=1, norm='ortho')
Z[i, :thresh, :thresh, :] = noiseInstance[:thresh, :thresh, :]
images = np.zeros((n, n1, n1, c))
for i in range(n):
for j in range(c):
newIm = idct(idct(Z[i, :, :, j], axis=0, norm='ortho'), axis=1, norm='ortho')
images[i, :, :, j] = newIm
return images
def prep_data(dataset='FMNIST', CNN=False, noise_index=0):
np.random.seed(2048)
if dataset == 'SYNTH':
X = np.load('./datasets/synthetic/X_train_anisotropic_1024_16_%d.npy'%(noise_index))
Y = np.load('./datasets/synthetic/y_train_anisotropic_1024_16_%d.npy'%(noise_index))
YT = np.load('./datasets/synthetic/y_test_anisotropic_1024_16_%d.npy'%(noise_index))
XT = np.load('./datasets/synthetic/X_test_anisotropic_1024_16_%d.npy'%(noise_index))
assert Y.dtype == np.float32 and YT.dtype == np.float32
assert X.dtype == np.float32 and XT.dtype == np.float32
assert len(Y.shape) == 2 and len(YT.shape) == 2
assert Y.shape[1] == 1 and YT.shape[1] == 1
elif dataset == 'CIFAR2':
eps = np.linspace(0, 3, num=15)
Y, X = cifar_input('train', True, False)
# Choosing cats and airplanes
inds = [i for i in range(len(Y)) if Y[i, 0] in [3, 0]]
Y = Y[inds, :]
X = X[inds, :]
for i in range(len(Y)):
if Y[i, 0] == 3:
Y[i, 0] = 0
else:
Y[i, 0] = 1
YT, XT = cifar_input('test', True, False)
# Choosing cats and airplanes
inds = [i for i in range(len(YT)) if YT[i, 0] in [3, 0]]
YT = YT[inds, :]
XT = XT[inds, :]
for i in range(len(YT)):
if YT[i, 0] == 3:
YT[i, 0] = 0
else:
YT[i, 0] = 1
d = X.shape[1]
n1 = np.int(np.sqrt(d))
cfilter = np.zeros((n1, n1))
for i in range(n1):
for j in range(n1):
radius = (n1 - i - 1) ** 2 + (n1 - j - 1) ** 2
radius = np.sqrt(radius)
if radius <= (n1 - 1):
cfilter[i, j] = 1.0
X = addHFNoise(X, cfilter, eps[noise_index])
XT = addHFNoise(XT, cfilter, eps[noise_index])
elif dataset == 'CIFAR10':
threshs = [0, 4, 8, 12, 14, 17, 19, 20, 22, 24, 25, 27, 28, 29, 30]
threshs = np.array(threshs)
thresh = threshs[noise_index]
print('Chosen Threshold is %d'%(thresh))
Y, X0 = cifarTrain()
YT, XT0 = cifarTest()
n = X0.shape[0]
n1 = X0.shape[1]
c = X0.shape[3]
d = n1 * n1 * c
Z = np.zeros((n, d))
freq = np.zeros((n1, n1, c))
for i in range(n):
for j in range(c):
image = X0[i, :, :, j]
freq[:, :, j] = dct(dct(image, axis=0, norm='ortho'), axis=1, norm='ortho')
Z[i, :] = freq.flatten()
mu = np.mean(Z, axis=0, keepdims=True)
Z = Z - mu
S = np.dot(Z.T, Z) / (n + 0.0)
w, Q = np.linalg.eigh(S)
wHalf = np.diag(w ** 0.5)
Shalf = np.dot(Q, np.dot(wHalf, Q.T))
X = addCifarNoise(X0, thresh, Shalf, mu)
XT = addCifarNoise(XT0, thresh, Shalf, mu)
# Computing Normalization Statistics
mu = np.mean(X, axis=0, keepdims=True)
mu = np.mean(mu, axis=1, keepdims=True)
mu = np.mean(mu, axis=2, keepdims=True)
sd = np.zeros((1, 1, 1, 3))
for i in range(3):
sd[0, 0, 0, i] = np.std(X[:, :, :, i])
X = (X - mu) / sd
XT = (XT - mu) / sd
elif dataset == 'FMNIST':
eps = np.linspace(0, 3, num=15)
print('Noise strength is %f'%(eps[noise_index]))
X = np.load('./datasets/FMNIST/initial_ds/X.npy')
Y = np.load('./datasets/FMNIST/initial_ds/Y.npy')
YT = np.load('./datasets/FMNIST/initial_ds/Yt.npy')
XT = np.load('./datasets/FMNIST/initial_ds/Xt.npy')
assert len(Y.shape) == 2 and len(YT.shape) == 2
assert Y.shape[1] == 1 and YT.shape[1] == 1
n = X.shape[0]
d = X.shape[1]
n1 = np.int(np.sqrt(d))
cfilter = np.zeros((n1, n1))
for i in range(n1):
for j in range(n1):
radius = (n1 - i - 1) ** 2 + (n1 - j - 1) ** 2
radius = np.sqrt(radius)
if radius <= (n1 - 1):
cfilter[i, j] = 1.0
X = addHFNoise(X, cfilter, eps[noise_index])
XT = addHFNoise(XT, cfilter, eps[noise_index])
elif dataset == 'NFMNIST':
thresholds = np.arange(1, 28, step=2)
thresh = thresholds[noise_index]
print('Chosen Threshold is %d'%(thresh))
X = np.load('./datasets/FMNIST/initial_ds/X.npy')
Y = np.load('./datasets/FMNIST/initial_ds/Y.npy')
YT = np.load('./datasets/FMNIST/initial_ds/Yt.npy')
XT = np.load('./datasets/FMNIST/initial_ds/Xt.npy')
assert len(Y.shape) == 2 and len(YT.shape) == 2
assert Y.shape[1] == 1 and YT.shape[1] == 1
n = X.shape[0]
d = X.shape[1]
n1 = np.int(np.sqrt(d))
Z = np.zeros((n, d))
for i in range(n):
image = X[i].reshape((n1, n1))
image = image - np.mean(image)
image = image / np.linalg.norm(image)
image = image * np.sqrt(d)
freq = dct(dct(image, axis=0, norm='ortho'), axis=1, norm='ortho')
Z[i, :] = freq.flatten()
mu = np.mean(Z, axis=0, keepdims=True)
Z = Z - mu
S = np.dot(Z.T, Z) / (n + 0.0)
w, Q = np.linalg.eigh(S)
wHalf = np.diag(w ** 0.5)
Shalf = np.dot(Q, np.dot(wHalf, Q.T))
X = addTHNoise(X, thresh, Shalf, mu)
XT = addTHNoise(XT, thresh, Shalf, mu)
else:
raise Exception('Unidentified dataset')
X = X.astype(np.float32)
Y = Y.astype(np.float32)
XT = XT.astype(np.float32)
YT = YT.astype(np.float32)
return (X, Y, XT, YT)