-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgrammar.py
More file actions
433 lines (357 loc) · 15.3 KB
/
grammar.py
File metadata and controls
433 lines (357 loc) · 15.3 KB
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# -*- coding: utf-8 -*-
# @Time : 18-10-12 下午9:59
# @Author : HeJi
# @FileName: grammar.py
# @E-mail: [email protected]
from utils import euclidean_distance
import numpy as np
from sklearn.decomposition import PCA
from sklearn import preprocessing
import random
import scipy
import copy
from utils import get_coordinates_labels, timer, get_train_test
from multiprocessing import Process
import multiprocessing
import math
"""
def select_round_superpixel(target_point, radius = 2):
start_point = tuple([target_point[0] - radius, target_point[1] - radius])
end_point = tuple([target_point[0] + radius, target_point[1] + radius])
correct_points = []
for i in range(start_point[0], end_point[0]+1):
for j in range(start_point[1], end_point[1]+1):
eval_point = np.zeros(2)
if i < target_point[0]:
eval_point[0]= i+0.5
elif i > target_point[0]:
eval_point[0] = i-0.5
elif i == target_point[0]:
eval_point[0] = i
if j < target_point[1]:
eval_point[1]= j+0.5
elif j > target_point[1]:
eval_point[1] = j-0.5
elif j == target_point[1]:
eval_point[1] = j
if euclidean_distance(target_point, eval_point)<radius:
correct_points.append(tuple([i, j]))
return correct_points
"""
def select_round(img, target_coords, r):
if len(target_coords.shape) == 1:
target_coords = np.expand_dims(target_coords, axis=0)
zeroPaddedX = padWithZeros(img, margin=r)
new_target_coords = target_coords + r
shape = zeroPaddedX.shape
height = shape[0]
width = shape[1]
sentences = []
for ntc in new_target_coords:
mask = np.zeros((height, width), dtype=np.bool)
y, x = np.ogrid[-ntc[0]:height - ntc[0], -ntc[1]:width - ntc[1]]
m = x * x + y * y <= r * r
mask = np.logical_or(mask, m)
sentences.append(np.expand_dims(zeroPaddedX[mask], axis=0))
sentences = np.concatenate(sentences, axis=0)
return sentences
def select_round_no_pad(img, target_coords, r):
if len(target_coords.shape) == 1:
target_coords = np.expand_dims(target_coords, axis=0)
shape = img.shape
height = shape[0]
width = shape[1]
sentences = []
for ntc in target_coords:
mask = np.zeros((height, width), dtype=np.bool)
y, x = np.ogrid[-ntc[0]:height - ntc[0], -ntc[1]:width - ntc[1]]
m = x * x + y * y <= r * r
mask = np.logical_or(mask, m)
sentences.append(np.expand_dims(img[mask], axis=0))
sentences = np.concatenate(sentences, axis=0)
return sentences
# pad zeros to dataset
def padWithZeros(X, margin=2):
return np.pad(X, [(margin, margin), (margin, margin), (0,0)], mode="constant")
# apply PCA preprocessing for data sets
def applyPCA(X, numComponents=75):
newX = np.reshape(X, (-1, X.shape[2]))
pca = PCA(n_components=numComponents, whiten=True)
newX = pca.fit_transform(newX)
newX = np.reshape(newX, (X.shape[0],X.shape[1], numComponents))
return newX, pca
# over sample
def oversampleWeakClasses(X, y):
uniqueLabels, labelCounts = np.unique(y, return_counts=True)
maxCount = np.max(labelCounts)
labelInverseRatios = maxCount / labelCounts
# repeat for every label and concat
newX = X[y == uniqueLabels[0], :, :, :].repeat(round(labelInverseRatios[0]),
axis=0)
newY = y[y == uniqueLabels[0]].repeat(round(labelInverseRatios[0]), axis=0)
for label, labelInverseRatio in zip(uniqueLabels[1:], labelInverseRatios[1:]):
cX = X[y== label,:,:,:].repeat(round(labelInverseRatio), axis=0)
cY = y[y == label].repeat(round(labelInverseRatio), axis=0)
newX = np.concatenate((newX, cX))
newY = np.concatenate((newY, cY))
np.random.seed(seed=42)
rand_perm = np.random.permutation(newY.shape[0])
newX = newX[rand_perm, :, :, :]
newY = newY[rand_perm]
return newX, newY
# standartize
def standartizeData(X):
newX = np.reshape(X, (-1, X.shape[2]))
#scaler = preprocessing.StandardScaler().fit(newX)
newX = preprocessing.scale(newX)
#newX = scaler.transform(newX)
newX = np.reshape(newX, (X.shape[0],X.shape[1],X.shape[2]))
return newX
def transform_array(array, mode = 0, degree = None):
if (mode == 0):
flipped_patch = np.flipud(array)
if (mode == 1):
flipped_patch = np.fliplr(array)
if (mode == 2):
assert(degree is not None)
flipped_patch = scipy.ndimage.interpolation.rotate(array,
degree, axes=(1, 0), reshape=False, output=None,
order=3, mode='constant', cval=0.0, prefilter=False)
noise = np.random.normal(0.0, 0.05, size=(array.shape))
flipped_patch += noise
return flipped_patch
def rotate(array, degree):
transformed_array = scipy.ndimage.interpolation.rotate(array,
degree, axes=(1, 0), reshape=False, output=None,
order=3, mode='constant', cval=0.0, prefilter=False)
return transformed_array
def add_noise(array):
noise = np.random.normal(0.0, 0.05, size=(array.shape))
return array + noise
def flipud(array):
return np.flipud(array)
def t0(array):
return array
def t1(array):
return rotate(array, 90)
def t2(array):
return rotate(array, 180)
def t3(array):
return rotate(array, 270)
def t4(array):
return flipud(t1(array))
def t5(array):
return flipud(t2(array))
def t6(array):
return flipud(t3(array))
def t7(array):
return add_noise(t0(array))
def t8(array):
return add_noise(t1(array))
def t9(array):
return add_noise(t2(array))
def t10(array):
return add_noise(t3(array))
def t11(array):
return add_noise(t4(array))
def t12(array):
return add_noise(t5(array))
def t13(array):
return add_noise(t6(array))
def transform(array):
switchs = [t0, t1, t2, t3, t4, t5, t6, t7,
t8, t9, t10, t11, t12, t13]
target_fun = np.random.choice(switchs)
return target_fun(array)
def single_transform(array, index, size, return_dict):
print(index)
length = len(array)
size = int(math.ceil(length / size))
start = size * index
end = (index + 1) * size if (index + 1) * size < length else length
temp_array = array[start:end]
return_dict[index] = list(map(transform, temp_array))
def parallel_tranform(array):
used_cpu = multiprocessing.cpu_count()
manager = multiprocessing.Manager()
return_dict = manager.dict()
all_results = []
jobs = []
for i in range(used_cpu):
# p = Process(target=run, args=(all_smiles,all_labels, i, used_cpu, args.save_path))
p = Process(target=single_transform, args=(array, i, used_cpu, return_dict))
jobs.append(p)
p.start()
for proc in jobs:
proc.join()
for i in range(used_cpu):
all_results += return_dict[i]
all_results = [np.expand_dims(kk, axis=0) for kk in all_results]
return np.concatenate(all_results, axis=0)
def fuse_samples(sampleA, sampleB, alpha, beta):
"""
:param sampleA: pixelA
:param sampleB: pixelB
:param alpha: size as sampleA
:param beta: size as sampleA
:return: fused sample
"""
return alpha*sampleA+(1-alpha)*sampleB + beta
def generating_bands_samples(hsi, train_coordinates, train_labels, num_band_group = 10):
new_hsi = copy.deepcopy(hsi)
assert(new_hsi.shape[2]%num_band_group == 0)
band_group_size = int(new_hsi.shape[2]/num_band_group)
imgs = np.split(new_hsi, axis=2, indices_or_sections=num_band_group)
unique_labels = np.unique(train_labels)
for img in imgs:
for lbl in unique_labels:
lbl_train_coordinates = train_coordinates[train_labels==lbl]
lbl_train_data = img[lbl_train_coordinates[:, 0], lbl_train_coordinates[:, 1], :]
#means = np.mean(lbl_train_data, axis=0)
stds = np.std(lbl_train_data, axis=0)
for coord in lbl_train_coordinates:
beta = np.array([np.random.normal(loc=0, scale=0.05) for i in range(new_hsi.shape[2])])
#alpha = np.random.random(size=band_group_size)
alpha = np.random.random()
sampleA = img[coord[0], coord[1], :]
bcoord = lbl_train_coordinates[np.random.choice(lbl_train_coordinates.shape[0])]
sampleB = img[bcoord[0],bcoord[1],:]
img[coord[0], coord[1], :] = fuse_samples(sampleA, sampleB, alpha, beta)
return imgs
def generating_pitches_samples(pitches, labels):
mypitches = copy.deepcopy(pitches)
unique_labels = np.unique(labels)
generated_pitches = []
generated_labels = []
for lbl in unique_labels:
lbl_pitches = mypitches[labels == lbl]
for pitchA in lbl_pitches:
pitchB = lbl_pitches[np.random.choice(lbl_pitches.shape[0])]
beta = np.array([np.random.normal(loc=0, scale=0.05) for i in range(mypitches.shape[-1])])
# print("beta.shape", beta.shape)
fused_sample = fuse_samples(sampleA=pitchA, sampleB=pitchB, alpha=np.random.random(), beta=beta)
fused_sample = np.expand_dims(fused_sample, axis=0)
generated_pitches.append(fused_sample)
generated_labels.append(lbl)
generated_pitches = np.concatenate(generated_pitches, axis=0)
generated_labels = np.array(generated_labels)
return generated_pitches, generated_labels
def rotation_and_flip(pitches, labels, shuffle = True):
assert (len(pitches.shape) == 4)
print("Applying rotation and flip")
augment_pitches = []
augment_labels = []
for i, pitch in enumerate(pitches):
p9 = transform_array(pitch, mode=2, degree=90)
p18 = transform_array(pitch, mode=2, degree=180)
p27 = transform_array(pitch, mode=2, degree=270)
p9f = transform_array(p9, mode=0)
p18f = transform_array(p18, mode=0)
p27f = transform_array(p27, mode=0)
pitch = np.expand_dims(pitch, axis=0)
p9 = np.expand_dims(p9, axis=0)
p18 = np.expand_dims(p18, axis=0)
p27 = np.expand_dims(p27, axis=0)
p9f = np.expand_dims(p9f, axis=0)
p18f = np.expand_dims(p18f, axis=0)
p27f = np.expand_dims(p27f, axis=0)
pitch_augmented = np.concatenate([pitch,p9,p18,p27,p9f,p18f,p27f],axis=0)
pitch_label_augmented = np.array([labels[i]]*7)
augment_pitches.append(pitch_augmented)
augment_labels.append(pitch_label_augmented)
augment_pitches = np.concatenate(augment_pitches, axis=0)
augment_labels = np.concatenate(augment_labels)
indexes = np.arange(augment_pitches.shape[0])
indexes = np.random.permutation(indexes)
if shuffle:
augment_pitches = augment_pitches[indexes]
augment_labels = augment_labels[indexes]
return augment_pitches, augment_labels
def zmm_random_flip(data,label,seed=0):
print("Appling ZMM random flip")
num = data.shape[0]
datas = []
labels = []
assert (len(data.shape) == 4)
for i in range(num):
datas.append(data[i])
noise = np.random.normal(0.0, 0.05, size=(data[i].shape))
datas.append(np.fliplr(data[i]) + noise)
labels.append(label[i])
labels.append(label[i])
datas = np.asarray(datas, dtype=np.float32)
labels = np.asarray(labels, dtype=np.float32)
np.random.seed(seed)
index = np.random.permutation(datas.shape[0])
return datas[index], labels[index]
def select_rect(hsi, target_coords, pitch_size = 5):
if len(target_coords.shape) == 1:
target_coords = np.expand_dims(target_coords, axis=0)
margin = int((pitch_size - 1) / 2)
zeroPaddedX = padWithZeros(hsi, margin=margin)
ncoords = target_coords + margin
pitches = [zeroPaddedX[ncoords[i,0] - margin:ncoords[i,0] + margin + 1, ncoords[i,1]-margin
:ncoords[i,1] + margin + 1] for i in range(len(ncoords))]
pitches = [np.expand_dims(pitch, axis=0) for pitch in pitches]
return np.concatenate(pitches, axis=0) #, pitch_coords
def select_rect_no_pad(hsi, target_coords, pitch_size = 5):
if len(target_coords.shape) == 1:
target_coords = np.expand_dims(target_coords, axis=0)
margin = int((pitch_size - 1) / 2)
pitches = [hsi[target_coords[i,0] - margin:target_coords[i,0] + margin + 1, target_coords[i,1]-margin
:target_coords[i,1] + margin + 1] for i in range(len(target_coords))]
pitches = [np.expand_dims(pitch, axis=0) for pitch in pitches]
return np.concatenate(pitches, axis=0)
def select_line(img, target_coords, length = 5, mod = "h"):
if len(target_coords.shape) == 1:
target_coords = np.expand_dims(target_coords, axis=0)
margin = int((length - 1) / 2)
zeroPaddedX = padWithZeros(img, margin=margin)
ncoords = target_coords + margin
if mod == "h":
lines = [zeroPaddedX[ncoords[i, 0], ncoords[i, 1] - margin:ncoords[i, 1] + margin + 1] for i in range(len(ncoords))]
elif mod =="v":
lines = [zeroPaddedX[ncoords[i, 0] - margin:ncoords[i,0]+margin+1, ncoords[i,1]] for i in range(len(ncoords))]
lines = [np.expand_dims(line, axis=0) for line in lines]
return np.concatenate(lines, axis=0)
def select_line_no_pad(img, target_coords, length = 5, mod = "h"):
if len(target_coords.shape) == 1:
target_coords = np.expand_dims(target_coords, axis=0)
margin = int((length - 1) / 2)
if mod == "h":
lines = [img[target_coords[i, 0], target_coords[i, 1] - margin:target_coords[i, 1] + margin + 1] for i in range(len(target_coords))]
elif mod =="v":
lines = [img[target_coords[i, 0] - margin:target_coords[i,0]+margin+1, target_coords[i,1]] for i in range(len(target_coords))]
lines = [np.expand_dims(line, axis=0) for line in lines]
return np.concatenate(lines, axis=0)
def Grammar(img, tgt_coords, method = "rect 11"):
try:
region_type , param = method.split()
param = int(param)
except:
region_type = method
if region_type == "rect":
assert (param is not None)
data = select_rect_no_pad(img, tgt_coords,pitch_size=param)
#data = list(map(transform, data))
#data = [np.expand_dims(dd, axis=0) for dd in data]
#data = np.concatenate(data, axis=0)
#data = np.reshape(data, [data.shape[0], data.shape[1]*data.shape[2], data.shape[3]])
elif region_type == 'round':
assert (param is not None)
data = select_round_no_pad(img, tgt_coords, r=param)
elif region_type == "dot":
data = select_rect_no_pad(img, tgt_coords, pitch_size = 1)
data = np.reshape(data, [data.shape[0], data.shape[1] * data.shape[2], data.shape[3]])
elif region_type == 'hl':
assert (param is not None)
data = select_line_no_pad(img, tgt_coords, length=param, mod="h")
elif region_type == 'vl':
assert (param is not None)
data = select_line_no_pad(img, tgt_coords, length=param, mod="v")
elif region_type =='cross':
assert (param is not None)
datah = select_line_no_pad(img, tgt_coords, length=param, mod="h")
datav = select_line_no_pad(img, tgt_coords, length=param, mod="v")
data = np.concatenate([datah, datav], axis=1)
return data