forked from ziweipolaris/atec2018-nlp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pai_transform.py
4438 lines (3622 loc) · 178 KB
/
pai_transform.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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# https://pai4contest.cloud.alipay.com/experiment.htm?Lang=zh_CN&lang=zh_CN&etag=iZbp10tfg72g1zj2tnd6rwZ&experimentId=3508
import time
start_time = time.time()
import gensim
import numpy as np
import pandas as pd
import os
import re
try:
import jieba_fast as jieba
except Exception as e:
import jieba
from sklearn.model_selection import train_test_split
try:
print(model_dir)
test_size = 0.025
online=True
except:
model_dir = "pai_model/"
test_size = 0.05
online=False
random_state = 42
cfgs = [
("siamese","char",24,300,[64, 64, 64],90),
("siamese","word",20,300,[80, 64, 64],90),
]
new_words = "支付宝 付款码 二维码 收钱码 转账 退款 退钱 余额宝 运费险 还钱 还款 花呗 借呗 蚂蚁花呗 蚂蚁借呗 蚂蚁森林 小黄车 飞猪 微客 宝卡 芝麻信用 亲密付 淘票票 饿了么 摩拜 滴滴 滴滴出行".split(" ")
for word in new_words:
jieba.add_word(word)
def transform_weight(cfg):
model_type,dtype,input_length,w2v_length,n_hidden,n_epoch = cfg
w2v_path = "%s2vec_gensim%d"%(dtype,w2v_length)
old_weights = gensim.models.Word2Vec.load("model/"+w2v_path).wv
open(model_dir + "%s2index%d.csv"%(dtype,w2v_length),'w',encoding='utf8').write('\n'.join([char+'#'+str(i) for i,char in enumerate(old_weights.index2word)]))
embedding_length = len(old_weights.index2word)
print(dtype,embedding_length)
with open(model_dir+w2v_path+".csv",'w',encoding="utf8") as out:
indexs = [(kv.split("\t")[0],kv.split("\t")[1]) for kv in open(model_dir + "%s2index%d.csv"%(dtype,w2v_length),"r",encoding='utf8').read().split("\n")]
for name,index in indexs:
out.write(index + "#" + ",".join(map(str,old_weights[name]))+"\n")
def transform_weight_npy(cfg):
model_type,dtype,input_length,w2v_length,n_hidden,n_epoch = cfg
if dtype == 'word':
embedding_length = 429200
elif dtype == 'char':
embedding_length = 9436
if dtype == 'word':
embedding_length = 501344
elif dtype == 'char':
embedding_length = 10125
w2v_path = model_dir+"%s2vec_gensim%d.csv"%(dtype,w2v_length)
embedding_matrix = np.zeros((embedding_length, w2v_length))
for no,line in enumerate(open(w2v_path,encoding="utf8")):
embedding_matrix[no,:] = np.array([float(x) for x in line.split("#")[1].strip().split(",")])
np.save(model_dir +"%s2vec_gensim%d.npy"%(dtype,w2v_length), embedding_matrix)
def transform_weight_npy2(cfg,ebed_type):
model_type,dtype,input_length,w2v_length,n_hidden,n_epoch = cfg
w2v_path = model_dir+"%s2vec_%s%d.vec"%(dtype,ebed_type,w2v_length)
with open(w2v_path,'r',encoding='utf8') as file:
line = file.readline()
tokens = []
embedding_length, w2v_length = map(int,line.split())
embedding_matrix = np.zeros((embedding_length, w2v_length))
print(line)
for index,line in enumerate(file):
data = line.strip().split(" ")
assert(len(data) == 301)
tokens.append(data[0])
embedding_matrix[index,:] = np.array([float(x) for x in data[1:]])
open(model_dir+"fasttext/%s2index_%s%d.csv"%(dtype,ebed_type,w2v_length), 'w', encoding="utf8").write("\n".join(["%s\t%d"%(token,index) for index,token in enumerate(tokens)]))
np.save(model_dir +"fasttext/%s2vec_%s%d.npy"%(dtype,ebed_type,w2v_length), embedding_matrix)
def read_save():
import pandas as pd
csv = pd.read_csv(model_dir+"atec_nlp_sim_train.csv",sep="\t",header=None,encoding='utf8')
csv.columns=["lino","sent1","sent2","label"]
csv.to_csv(model_dir + "foo.csv",sep="\t",header=None,index=False,encoding='utf8')
for no,x in enumerate(open(model_dir + "foo.csv",'r',encoding='utf8')):
print(x)
if no>3:
break
def save_to_file(df1,df2,df3,df4):
#df1 df2 df3 df4类型为: pandas.core.frame.DataFrame.分别引用输入桩数据
#topai(1, df1)函数把df1内容写入第一个输出桩
df1.to_csv(model_dir+'char2index.csv',sep="#",header=None,index=Fasle,encoding='utf8',)
w2 = df2.set_index("index",inplace=False)
w2.sort_index(inplace=True)
w2.to_csv(model_dir+'char2vec_gensim256.csv',sep="#",header=None,index=True,encoding='utf8',)
df3.to_csv(model_dir+'word2index.csv',sep="#",header=None,index=Fasle,encoding='utf8',)
w4 = df4.set_index("index",inplace=False)
w4.sort_index(inplace=True)
w4.to_csv(model_dir+'word2vec_gensim256.csv',sep="#",header=None,index=True,encoding='utf8',)
for filename in [
'char2index.csv',
'char2vec_gensim256.csv',
'word2index.csv',
'word2vec_gensim256.csv',
'atec_nlp_sim_train.csv',
]:
with open(model_dir + filename,'r',encoding='utf8') as f:
for no,line in enumerate(f):
print(line)
if no>3:
print(filename," ok")
break
def transform_weight_merge():
w2v_path = "model/sgns.merge.char.txt"
chars = []
# with open(w2v_path,'r',encoding='utf8') as file:
# line = file.readline()
# fout = open(model_dir + )
# print(line)
# for line in file:
# data = line.strip().split(" ")
# assert(len(data) == 301)
# chars.append(data[0])
# break
# return
# dtype, w2v_length = 'char',300
# open("model/%s2index_merge%s.txt"%(dtype,w2v_length),'w',encoding='utf8').write('\n'.join([char+'\t'+str(i) for i,char in enumerate(chars)]))
# embedding_length = len(old_weights.index2word)
# print(dtype,embedding_length)
# with open(model_dir+w2v_path+".csv",'w',encoding="utf8") as out:
# indexs = [(kv.split("\t")[0],kv.split("\t")[1]) for kv in open("model/%s2index%s.txt"%(dtype,w2v_length),"r",encoding='utf8').read().split("\n")]
# for name,index in indexs:
# out.write(index + "#" + ",".join(map(str,old_weights[name]))+"\n")
def transform_wiki():
import re
for i in range(11):
with open("resources/wiki_corpus/wiki%02d"%i,"r",encoding="utf8") as wiki_in:
with open("resources/wiki_corpus/wiki%02d.csv"%i,"w",encoding="utf8") as wiki_out:
for line in wiki_in:
title, doc = line.strip().split("|")
if len(doc)>=10:
wiki_out.write(title+"|"+doc+"\n")
# start imports###################################################################
from enum import IntEnum
from timeit import default_timer as timer
import copy
import math
from abc import abstractmethod
import contextlib
from glob import glob, iglob
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from itertools import chain
from functools import partial
from functools import wraps
from collections import Iterable, Counter, OrderedDict
import pickle
# end imports####################################################################
# start torch imports ############################################################
from torch.utils.data.sampler import Sampler, SequentialSampler, RandomSampler, BatchSampler
from torch.utils.data import Dataset
from distutils.version import LooseVersion
import torch
from torch import nn, cuda, backends, FloatTensor, LongTensor, optim
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import Dataset, TensorDataset
from torch.nn.init import kaiming_uniform, kaiming_normal
import queue
import collections,sys,traceback,threading
import warnings
warnings.filterwarnings('ignore', message='Implicit dimension choice', category=UserWarning)
IS_TORCH_04 = LooseVersion(torch.__version__) >= LooseVersion('0.4')
if IS_TORCH_04:
from torch.nn.init import kaiming_uniform_ as kaiming_uniform
from torch.nn.init import kaiming_normal_ as kaiming_normal
def children(m): return m if isinstance(m, (list, tuple)) else list(m.children())
def save_model(m, p): torch.save(m.state_dict(), p)
def load_model(m, p):
sd = torch.load(p, map_location=lambda storage, loc: storage)
names = set(m.state_dict().keys())
for n in list(sd.keys()): # list "detatches" the iterator
if n not in names and n+'_raw' in names:
if n+'_raw' not in sd: sd[n+'_raw'] = sd[n]
del sd[n]
m.load_state_dict(sd)
# end torch imports ##############################################################
# start fastai.core###############################################################
def sum_geom(a,r,n): return a*n if r==1 else math.ceil(a*(1-r**n)/(1-r))
def is_listy(x): return isinstance(x, (list,tuple))
def is_iter(x): return isinstance(x, collections.Iterable)
def map_over(x, f): return [f(o) for o in x] if is_listy(x) else f(x)
def map_none(x, f): return None if x is None else f(x)
def delistify(x): return x[0] if is_listy(x) else x
def listify(x, y):
if not is_iter(x): x=[x]
n = y if type(y)==int else len(y)
if len(x)==1: x = x * n
return x
def datafy(x):
if is_listy(x): return [o.data for o in x]
else: return x.data
conv_dict = {np.dtype('int8'): torch.LongTensor, np.dtype('int16'): torch.LongTensor,
np.dtype('int32'): torch.LongTensor, np.dtype('int64'): torch.LongTensor,
np.dtype('float32'): torch.FloatTensor, np.dtype('float64'): torch.FloatTensor}
def A(*a):
"""convert iterable object into numpy array"""
return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]
def T(a, half=False, cuda=True):
"""
Convert numpy array into a pytorch tensor.
if Cuda is available and USE_GPU=True, store resulting tensor in GPU.
"""
if not torch.is_tensor(a):
a = np.array(np.ascontiguousarray(a))
if a.dtype in (np.int8, np.int16, np.int32, np.int64):
a = torch.LongTensor(a.astype(np.int64))
elif a.dtype in (np.float32, np.float64):
a = torch.cuda.HalfTensor(a) if half else torch.FloatTensor(a)
else: raise NotImplementedError(a.dtype)
if cuda: a = to_gpu(a, async=True)
return a
def create_variable(x, volatile, requires_grad=False):
if type (x) != Variable:
if IS_TORCH_04: x = Variable(T(x), requires_grad=requires_grad)
else: x = Variable(T(x), requires_grad=requires_grad, volatile=volatile)
return x
def V_(x, requires_grad=False, volatile=False):
'''equivalent to create_variable, which creates a pytorch tensor'''
return create_variable(x, volatile=volatile, requires_grad=requires_grad)
def V(x, requires_grad=False, volatile=False):
'''creates a single or a list of pytorch tensors, depending on input x. '''
return map_over(x, lambda o: V_(o, requires_grad, volatile))
def VV_(x):
'''creates a volatile tensor, which does not require gradients. '''
return create_variable(x, True)
def VV(x):
'''creates a single or a list of pytorch tensors, depending on input x. '''
return map_over(x, VV_)
def to_np(v):
'''returns an np.array object given an input of np.array, list, tuple, torch variable or tensor.'''
if isinstance(v, (np.ndarray, np.generic)): return v
if isinstance(v, (list,tuple)): return [to_np(o) for o in v]
if isinstance(v, Variable): v=v.data
if torch.cuda.is_available():
if isinstance(v, torch.cuda.HalfTensor): v=v.float()
if isinstance(v, torch.FloatTensor): v=v.float()
return v.cpu().numpy()
IS_TORCH_04 = LooseVersion(torch.__version__) >= LooseVersion('0.4')
USE_GPU = torch.cuda.is_available()
def to_gpu(x, *args, **kwargs):
'''puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true. '''
return x.cuda(*args, **kwargs) if USE_GPU else x
def noop(*args, **kwargs): return
def split_by_idxs(seq, idxs):
'''A generator that returns sequence pieces, seperated by indexes specified in idxs. '''
last = 0
for idx in idxs:
if not (-len(seq) <= idx < len(seq)):
raise KeyError(f'Idx {idx} is out-of-bounds')
yield seq[last:idx]
last = idx
yield seq[last:]
def trainable_params_(m):
'''Returns a list of trainable parameters in the model m. (i.e., those that require gradients.)'''
return [p for p in m.parameters() if p.requires_grad]
def chain_params(p):
if is_listy(p):
return list(chain(*[trainable_params_(o) for o in p]))
return trainable_params_(p)
def set_trainable_attr(m,b):
m.trainable=b
for p in m.parameters(): p.requires_grad=b
def apply_leaf(m, f):
c = children(m)
if isinstance(m, nn.Module): f(m)
if len(c)>0:
for l in c: apply_leaf(l,f)
def set_trainable(l, b):
apply_leaf(l, lambda m: set_trainable_attr(m,b))
def SGD_Momentum(momentum):
return lambda *args, **kwargs: optim.SGD(*args, momentum=momentum, **kwargs)
def one_hot(a,c): return np.eye(c)[a]
def partition(a, sz):
"""splits iterables a in equal parts of size sz"""
return [a[i:i+sz] for i in range(0, len(a), sz)]
def partition_by_cores(a):
return partition(a, len(a)//num_cpus() + 1)
def num_cpus():
try:
return len(os.sched_getaffinity(0))
except AttributeError:
return os.cpu_count()
class BasicModel():
def __init__(self,model,name='unnamed'): self.model,self.name = model,name
def get_layer_groups(self, do_fc=False): return children(self.model)
class SingleModel(BasicModel):
def get_layer_groups(self): return [self.model]
class SimpleNet(nn.Module):
def __init__(self, layers):
super().__init__()
self.layers = nn.ModuleList([
nn.Linear(layers[i], layers[i + 1]) for i in range(len(layers) - 1)])
def forward(self, x):
x = x.view(x.size(0), -1)
for l in self.layers:
l_x = l(x)
x = F.relu(l_x)
return F.log_softmax(l_x, dim=-1)
def save(fn, a):
"""Utility function that savess model, function, etc as pickle"""
pickle.dump(a, open(fn,'wb'))
def load(fn):
"""Utility function that loads model, function, etc as pickle"""
return pickle.load(open(fn,'rb'))
def load2(fn):
"""Utility funciton allowing model piclking across Python2 and Python3"""
return pickle.load(open(fn,'rb'), encoding='iso-8859-1')
def load_array(fname):
'''
Load array using bcolz, which is based on numpy, for fast array saving and loading operations.
https://github.com/Blosc/bcolz
'''
return bcolz.open(fname)[:]
def chunk_iter(iterable, chunk_size):
'''A generator that yields chunks of iterable, chunk_size at a time. '''
while True:
chunk = []
try:
for _ in range(chunk_size): chunk.append(next(iterable))
yield chunk
except StopIteration:
if chunk: yield chunk
break
def set_grad_enabled(mode): return torch.set_grad_enabled(mode) if IS_TORCH_04 else contextlib.suppress()
def no_grad_context(): return torch.no_grad() if IS_TORCH_04 else contextlib.suppress()
# end fastai.core#################################################################
# start fastai.transforms#################################################################
# end fastai.transforms################################################################
# start fastai.dataloader#################################################################
string_classes = (str, bytes)
def get_tensor(batch, pin, half=False):
if isinstance(batch, (np.ndarray, np.generic)):
batch = T(batch, half=half, cuda=False).contiguous()
if pin: batch = batch.pin_memory()
return to_gpu(batch)
elif isinstance(batch, string_classes):
return batch
elif isinstance(batch, collections.Mapping):
return {k: get_tensor(sample, pin, half) for k, sample in batch.items()}
elif isinstance(batch, collections.Sequence):
return [get_tensor(sample, pin, half) for sample in batch]
raise TypeError(f"batch must contain numbers, dicts or lists; found {type(batch)}")
class DataLoader(object):
def __init__(self, dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, pad_idx=0,
num_workers=None, pin_memory=False, drop_last=False, pre_pad=True, half=False,
transpose=False, transpose_y=False):
self.dataset,self.batch_size,self.num_workers = dataset,batch_size,num_workers
self.pin_memory,self.drop_last,self.pre_pad = pin_memory,drop_last,pre_pad
self.transpose,self.transpose_y,self.pad_idx,self.half = transpose,transpose_y,pad_idx,half
if batch_sampler is not None:
if batch_size > 1 or shuffle or sampler is not None or drop_last:
raise ValueError('batch_sampler is mutually exclusive with '
'batch_size, shuffle, sampler, and drop_last')
if sampler is not None and shuffle:
raise ValueError('sampler is mutually exclusive with shuffle')
if batch_sampler is None:
if sampler is None:
sampler = RandomSampler(dataset) if shuffle else SequentialSampler(dataset)
batch_sampler = BatchSampler(sampler, batch_size, drop_last)
if num_workers is None:
self.num_workers = num_cpus()
self.sampler = sampler
self.batch_sampler = batch_sampler
def __len__(self): return len(self.batch_sampler)
def jag_stack(self, b):
if len(b[0].shape) not in (1,2): return np.stack(b)
ml = max(len(o) for o in b)
if min(len(o) for o in b)==ml: return np.stack(b)
res = np.zeros((len(b), ml), dtype=b[0].dtype) + self.pad_idx
for i,o in enumerate(b):
if self.pre_pad: res[i, -len(o):] = o
else: res[i, :len(o)] = o
return res
def np_collate(self, batch):
b = batch[0]
if isinstance(b, (np.ndarray, np.generic)): return self.jag_stack(batch)
elif isinstance(b, (int, float)): return np.array(batch)
elif isinstance(b, string_classes): return batch
elif isinstance(b, collections.Mapping):
return {key: self.np_collate([d[key] for d in batch]) for key in b}
elif isinstance(b, collections.Sequence):
return [self.np_collate(samples) for samples in zip(*batch)]
raise TypeError(("batch must contain numbers, dicts or lists; found {}".format(type(b))))
def get_batch(self, indices):
res = self.np_collate([self.dataset[i] for i in indices])
if self.transpose: res[0] = res[0].T
if self.transpose_y: res[1] = res[1].T
return res
def __iter__(self):
if self.num_workers==0:
for batch in map(self.get_batch, iter(self.batch_sampler)):
yield get_tensor(batch, self.pin_memory, self.half)
else:
with ThreadPoolExecutor(max_workers=self.num_workers) as e:
# avoid py3.6 issue where queue is infinite and can result in memory exhaustion
for c in chunk_iter(iter(self.batch_sampler), self.num_workers*10):
for batch in e.map(self.get_batch, c):
yield get_tensor(batch, self.pin_memory, self.half)
# end fastai.dataloader#################################################################
# start fastai.dataset#################################################################
def get_cv_idxs(n, cv_idx=0, val_pct=0.2, seed=42):
""" Get a list of index values for Validation set from a dataset
Arguments:
n : int, Total number of elements in the data set.
cv_idx : int, starting index [idx_start = cv_idx*int(val_pct*n)]
val_pct : (int, float), validation set percentage
seed : seed value for RandomState
Returns:
list of indexes
"""
np.random.seed(seed)
n_val = int(val_pct*n)
idx_start = cv_idx*n_val
idxs = np.random.permutation(n)
return idxs[idx_start:idx_start+n_val]
def path_for(root_path, new_path, targ):
return os.path.join(root_path, new_path, str(targ))
def resize_img(fname, targ, path, new_path, fn=None):
"""
Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ.
"""
if fn is None:
fn = resize_fn(targ)
dest = os.path.join(path_for(path, new_path, targ), fname)
if os.path.exists(dest): return
im = Image.open(os.path.join(path, fname)).convert('RGB')
os.makedirs(os.path.split(dest)[0], exist_ok=True)
fn(im).save(dest)
def resize_fn(targ):
def resize(im):
r,c = im.size
ratio = targ/min(r,c)
sz = (scale_to(r, ratio, targ), scale_to(c, ratio, targ))
return im.resize(sz, Image.LINEAR)
return resize
def resize_imgs(fnames, targ, path, new_path, resume=True, fn=None):
"""
Enlarge or shrink a set of images in the same directory to scale, such that the smaller of the height or width dimension is equal to targ.
Note:
-- This function is multithreaded for efficiency.
-- When destination file or folder already exist, function exists without raising an error.
"""
target_path = path_for(path, new_path, targ)
if resume:
subdirs = {os.path.dirname(p) for p in fnames}
subdirs = {s for s in subdirs if os.path.exists(os.path.join(target_path, s))}
already_resized_fnames = set()
for subdir in subdirs:
files = [os.path.join(subdir, file) for file in os.listdir(os.path.join(target_path, subdir))]
already_resized_fnames.update(set(files))
original_fnames = set(fnames)
fnames = list(original_fnames - already_resized_fnames)
errors = {}
def safely_process(fname):
try:
resize_img(fname, targ, path, new_path, fn=fn)
except Exception as ex:
errors[fname] = str(ex)
if len(fnames) > 0:
with ThreadPoolExecutor(num_cpus()) as e:
ims = e.map(lambda fname: safely_process(fname), fnames)
for _ in tqdm(ims, total=len(fnames), leave=False): pass
if errors:
print('Some images failed to process:')
print(json.dumps(errors, indent=2))
return os.path.join(path,new_path,str(targ))
def read_dir(path, folder):
""" Returns a list of relative file paths to `path` for all files within `folder` """
full_path = os.path.join(path, folder)
fnames = glob(f"{full_path}/*.*")
directories = glob(f"{full_path}/*/")
if any(fnames):
return [os.path.relpath(f,path) for f in fnames]
elif any(directories):
raise FileNotFoundError("{} has subdirectories but contains no files. Is your directory structure is correct?".format(full_path))
else:
raise FileNotFoundError("{} folder doesn't exist or is empty".format(full_path))
def read_dirs(path, folder):
'''
Fetches name of all files in path in long form, and labels associated by extrapolation of directory names.
'''
lbls, fnames, all_lbls = [], [], []
full_path = os.path.join(path, folder)
for lbl in sorted(os.listdir(full_path)):
if lbl not in ('.ipynb_checkpoints','.DS_Store'):
all_lbls.append(lbl)
for fname in os.listdir(os.path.join(full_path, lbl)):
if fname not in ('.DS_Store'):
fnames.append(os.path.join(folder, lbl, fname))
lbls.append(lbl)
return fnames, lbls, all_lbls
def n_hot(ids, c):
'''
one hot encoding by index. Returns array of length c, where all entries are 0, except for the indecies in ids
'''
res = np.zeros((c,), dtype=np.float32)
res[ids] = 1
return res
def folder_source(path, folder):
"""
Returns the filenames and labels for a folder within a path
Returns:
-------
fnames: a list of the filenames within `folder`
all_lbls: a list of all of the labels in `folder`, where the # of labels is determined by the # of directories within `folder`
lbl_arr: a numpy array of the label indices in `all_lbls`
"""
fnames, lbls, all_lbls = read_dirs(path, folder)
lbl2idx = {lbl:idx for idx,lbl in enumerate(all_lbls)}
idxs = [lbl2idx[lbl] for lbl in lbls]
lbl_arr = np.array(idxs, dtype=int)
return fnames, lbl_arr, all_lbls
def parse_csv_labels(fn, skip_header=True, cat_separator = ' '):
"""Parse filenames and label sets from a CSV file.
This method expects that the csv file at path :fn: has two columns. If it
has a header, :skip_header: should be set to True. The labels in the
label set are expected to be space separated.
Arguments:
fn: Path to a CSV file.
skip_header: A boolean flag indicating whether to skip the header.
Returns:
a two-tuple of (
image filenames,
a dictionary of filenames and corresponding labels
)
.
:param cat_separator: the separator for the categories column
"""
df = pd.read_csv(fn, index_col=0, header=0 if skip_header else None, dtype=str)
fnames = df.index.values
df.iloc[:,0] = df.iloc[:,0].str.split(cat_separator)
return fnames, list(df.to_dict().values())[0]
def nhot_labels(label2idx, csv_labels, fnames, c):
all_idx = {k: n_hot([label2idx[o] for o in ([] if type(v) == float else v)], c)
for k,v in csv_labels.items()}
return np.stack([all_idx[o] for o in fnames])
def csv_source(folder, csv_file, skip_header=True, suffix='', continuous=False, cat_separator=' '):
fnames,csv_labels = parse_csv_labels(csv_file, skip_header, cat_separator)
return dict_source(folder, fnames, csv_labels, suffix, continuous)
def dict_source(folder, fnames, csv_labels, suffix='', continuous=False):
all_labels = sorted(list(set(p for o in csv_labels.values() for p in ([] if type(o) == float else o))))
full_names = [os.path.join(folder,str(fn)+suffix) for fn in fnames]
if continuous:
label_arr = np.array([np.array(csv_labels[i]).astype(np.float32)
for i in fnames])
else:
label2idx = {v:k for k,v in enumerate(all_labels)}
label_arr = nhot_labels(label2idx, csv_labels, fnames, len(all_labels))
is_single = np.all(label_arr.sum(axis=1)==1)
if is_single: label_arr = np.argmax(label_arr, axis=1)
return full_names, label_arr, all_labels
class BaseDataset(Dataset):
"""An abstract class representing a fastai dataset. Extends torch.utils.data.Dataset."""
def __init__(self, transform=None):
self.transform = transform
self.n = self.get_n()
self.c = self.get_c()
self.sz = self.get_sz()
def get1item(self, idx):
x,y = self.get_x(idx),self.get_y(idx)
return self.get(self.transform, x, y)
def __getitem__(self, idx):
if isinstance(idx,slice):
xs,ys = zip(*[self.get1item(i) for i in range(*idx.indices(self.n))])
return np.stack(xs),ys
return self.get1item(idx)
def __len__(self): return self.n
def get(self, tfm, x, y):
return (x,y) if tfm is None else tfm(x,y)
@abstractmethod
def get_n(self):
"""Return number of elements in the dataset == len(self)."""
raise NotImplementedError
@abstractmethod
def get_c(self):
"""Return number of classes in a dataset."""
raise NotImplementedError
@abstractmethod
def get_sz(self):
"""Return maximum size of an image in a dataset."""
raise NotImplementedError
@abstractmethod
def get_x(self, i):
"""Return i-th example (image, wav, etc)."""
raise NotImplementedError
@abstractmethod
def get_y(self, i):
"""Return i-th label."""
raise NotImplementedError
@property
def is_multi(self):
"""Returns true if this data set contains multiple labels per sample."""
return False
@property
def is_reg(self):
"""True if the data set is used to train regression models."""
return False
def open_image(fn):
""" Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0
"""
flags = cv2.IMREAD_UNCHANGED+cv2.IMREAD_ANYDEPTH+cv2.IMREAD_ANYCOLOR
if not os.path.exists(fn) and not str(fn).startswith("http"):
raise OSError('No such file or directory: {}'.format(fn))
elif os.path.isdir(fn) and not str(fn).startswith("http"):
raise OSError('Is a directory: {}'.format(fn))
else:
#res = np.array(Image.open(fn), dtype=np.float32)/255
#if len(res.shape)==2: res = np.repeat(res[...,None],3,2)
#return res
try:
if str(fn).startswith("http"):
req = urllib.urlopen(str(fn))
image = np.asarray(bytearray(req.read()), dtype="uint8")
im = cv2.imdecode(image, flags).astype(np.float32)/255
else:
im = cv2.imread(str(fn), flags).astype(np.float32)/255
if im is None: raise OSError(f'File not recognized by opencv: {fn}')
return cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
except Exception as e:
raise OSError('Error handling image at: {}'.format(fn)) from e
class FilesDataset(BaseDataset):
def __init__(self, fnames, transform, path):
self.path,self.fnames = path,fnames
super().__init__(transform)
def get_sz(self): return self.transform.sz
def get_x(self, i): return open_image(os.path.join(self.path, self.fnames[i]))
def get_n(self): return len(self.fnames)
def resize_imgs(self, targ, new_path, resume=True, fn=None):
"""
resize all images in the dataset and save them to `new_path`
Arguments:
targ (int): the target size
new_path (string): the new folder to save the images
resume (bool): if true (default), allow resuming a partial resize operation by checking for the existence
of individual images rather than the existence of the directory
fn (function): custom resizing function Img -> Img
"""
dest = resize_imgs(self.fnames, targ, self.path, new_path, resume, fn)
return self.__class__(self.fnames, self.y, self.transform, dest)
def denorm(self,arr):
"""Reverse the normalization done to a batch of images.
Arguments:
arr: of shape/size (N,3,sz,sz)
"""
if type(arr) is not np.ndarray: arr = to_np(arr)
if len(arr.shape)==3: arr = arr[None]
return self.transform.denorm(np.rollaxis(arr,1,4))
class FilesArrayDataset(FilesDataset):
def __init__(self, fnames, y, transform, path):
self.y=y
assert(len(fnames)==len(y))
super().__init__(fnames, transform, path)
def get_y(self, i): return self.y[i]
def get_c(self):
return self.y.shape[1] if len(self.y.shape)>1 else 0
class FilesIndexArrayDataset(FilesArrayDataset):
def get_c(self): return int(self.y.max())+1
class FilesNhotArrayDataset(FilesArrayDataset):
@property
def is_multi(self): return True
class FilesIndexArrayRegressionDataset(FilesArrayDataset):
def is_reg(self): return True
class ArraysDataset(BaseDataset):
def __init__(self, x, y, transform):
self.x,self.y=x,y
assert(len(x)==len(y))
super().__init__(transform)
def get_x(self, i): return self.x[i]
def get_y(self, i): return self.y[i]
def get_n(self): return len(self.y)
def get_sz(self): return self.x.shape[1]
class ArraysIndexDataset(ArraysDataset):
def get_c(self): return int(self.y.max())+1
def get_y(self, i): return self.y[i]
class ArraysIndexRegressionDataset(ArraysIndexDataset):
def is_reg(self): return True
class ArraysNhotDataset(ArraysDataset):
def get_c(self): return self.y.shape[1]
@property
def is_multi(self): return True
class ModelData():
"""Encapsulates DataLoaders and Datasets for training, validation, test. Base class for fastai *Data classes."""
def __init__(self, path, trn_dl, val_dl, test_dl=None):
self.path,self.trn_dl,self.val_dl,self.test_dl = path,trn_dl,val_dl,test_dl
@classmethod
def from_dls(cls, path,trn_dl,val_dl,test_dl=None):
#trn_dl,val_dl = DataLoader(trn_dl),DataLoader(val_dl)
#if test_dl: test_dl = DataLoader(test_dl)
return cls(path, trn_dl, val_dl, test_dl)
@property
def is_reg(self): return self.trn_ds.is_reg
@property
def is_multi(self): return self.trn_ds.is_multi
@property
def trn_ds(self): return self.trn_dl.dataset
@property
def val_ds(self): return self.val_dl.dataset
@property
def test_ds(self): return self.test_dl.dataset
@property
def trn_y(self): return self.trn_ds.y
@property
def val_y(self): return self.val_ds.y
class ImageData(ModelData):
def __init__(self, path, datasets, bs, num_workers, classes):
trn_ds,val_ds,fix_ds,aug_ds,test_ds,test_aug_ds = datasets
self.path,self.bs,self.num_workers,self.classes = path,bs,num_workers,classes
self.trn_dl,self.val_dl,self.fix_dl,self.aug_dl,self.test_dl,self.test_aug_dl = [
self.get_dl(ds,shuf) for ds,shuf in [
(trn_ds,True),(val_ds,False),(fix_ds,False),(aug_ds,False),
(test_ds,False),(test_aug_ds,False)
]
]
def get_dl(self, ds, shuffle):
if ds is None: return None
return DataLoader(ds, batch_size=self.bs, shuffle=shuffle,
num_workers=self.num_workers, pin_memory=False)
@property
def sz(self): return self.trn_ds.sz
@property
def c(self): return self.trn_ds.c
def resized(self, dl, targ, new_path, resume = True, fn=None):
"""
Return a copy of this dataset resized
"""
return dl.dataset.resize_imgs(targ, new_path, resume=resume, fn=fn) if dl else None
def resize(self, targ_sz, new_path='tmp', resume=True, fn=None):
"""
Resizes all the images in the train, valid, test folders to a given size.
Arguments:
targ_sz (int): the target size
new_path (str): the path to save the resized images (default tmp)
resume (bool): if True, check for images in the DataSet that haven't been resized yet (useful if a previous resize
operation was aborted)
fn (function): optional custom resizing function
"""
new_ds = []
dls = [self.trn_dl,self.val_dl,self.fix_dl,self.aug_dl]
if self.test_dl: dls += [self.test_dl, self.test_aug_dl]
else: dls += [None,None]
t = tqdm_notebook(dls)
for dl in t: new_ds.append(self.resized(dl, targ_sz, new_path, resume, fn))
t.close()
return self.__class__(new_ds[0].path, new_ds, self.bs, self.num_workers, self.classes)
@staticmethod
def get_ds(fn, trn, val, tfms, test=None, **kwargs):
res = [
fn(trn[0], trn[1], tfms[0], **kwargs), # train
fn(val[0], val[1], tfms[1], **kwargs), # val
fn(trn[0], trn[1], tfms[1], **kwargs), # fix
fn(val[0], val[1], tfms[0], **kwargs) # aug
]
if test is not None:
if isinstance(test, tuple):
test_lbls = test[1]
test = test[0]
else:
if len(trn[1].shape) == 1:
test_lbls = np.zeros((len(test),1))
else:
test_lbls = np.zeros((len(test),trn[1].shape[1]))
res += [
fn(test, test_lbls, tfms[1], **kwargs), # test
fn(test, test_lbls, tfms[0], **kwargs) # test_aug
]
else: res += [None,None]
return res
class ImageClassifierData(ImageData):
@classmethod
def from_arrays(cls, path, trn, val, bs=64, tfms=(None,None), classes=None, num_workers=4, test=None, continuous=False):
""" Read in images and their labels given as numpy arrays
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
trn: a tuple of training data matrix and target label/classification array (e.g. `trn=(x,y)` where `x` has the
shape of `(5000, 784)` and `y` has the shape of `(5000,)`)
val: a tuple of validation data matrix and target label/classification array.
bs: batch size
tfms: transformations (for data augmentations). e.g. output of `tfms_from_model`
classes: a list of all labels/classifications
num_workers: a number of workers
test: a matrix of test data (the shape should match `trn[0]`)
Returns:
ImageClassifierData
"""
f = ArraysIndexRegressionDataset if continuous else ArraysIndexDataset
datasets = cls.get_ds(f, trn, val, tfms, test=test)
return cls(path, datasets, bs, num_workers, classes=classes)
@classmethod
def from_paths(cls, path, bs=64, tfms=(None,None), trn_name='train', val_name='valid', test_name=None, test_with_labels=False, num_workers=8):
""" Read in images and their labels given as sub-folder names
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
bs: batch size
tfms: transformations (for data augmentations). e.g. output of `tfms_from_model`
trn_name: a name of the folder that contains training images.
val_name: a name of the folder that contains validation images.
test_name: a name of the folder that contains test images.
num_workers: number of workers
Returns:
ImageClassifierData
"""
assert not(tfms[0] is None or tfms[1] is None), "please provide transformations for your train and validation sets"
trn,val = [folder_source(path, o) for o in (trn_name, val_name)]
if test_name:
test = folder_source(path, test_name) if test_with_labels else read_dir(path, test_name)
else: test = None
datasets = cls.get_ds(FilesIndexArrayDataset, trn, val, tfms, path=path, test=test)
return cls(path, datasets, bs, num_workers, classes=trn[2])
@classmethod
def from_csv(cls, path, folder, csv_fname, bs=64, tfms=(None,None),
val_idxs=None, suffix='', test_name=None, continuous=False, skip_header=True, num_workers=8, cat_separator=' '):
""" Read in images and their labels given as a CSV file.
This method should be used when training image labels are given in an CSV file as opposed to
sub-directories with label names.
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
folder: a name of the folder in which training images are contained.
csv_fname: a name of the CSV file which contains target labels.
bs: batch size
tfms: transformations (for data augmentations). e.g. output of `tfms_from_model`
val_idxs: index of images to be used for validation. e.g. output of `get_cv_idxs`.