-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoolbox.py
executable file
·1545 lines (1255 loc) · 48.5 KB
/
toolbox.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
#!/usr/bin/env python
from __future__ import print_function
from settings import CAFFE_ROOT
import sys
import os
sys.path.append(os.path.join(CAFFE_ROOT, 'python'))
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import random
import base64
import time
import scipy as sp
import scipy.io
import cv2
import h5py
import statsmodels.api as sm
COMMON_CODE = """
from __future__ import print_function
import sys
import os
sys.path.append('""" +os.path.join(CAFFE_ROOT, 'python')+ """')
import caffe
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import base64
import cv2
import h5py
import statsmodels.api as sm
import random
import time
import sklearn
import sklearn.manifold
from sklearn.manifold import TSNE
caffe.set_mode_gpu()
def rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=True):
\"\"\"
Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks
:param nlabels: Number of labels (size of colormap)
:param type: 'bright' for strong colors, 'soft' for pastel colors
:param first_color_black: Option to use first color as black, True or False
:param last_color_black: Option to use last color as black, True or False
:param verbose: Prints the number of labels and shows the colormap. True or False
:return: colormap for matplotlib
\"\"\"
from matplotlib.colors import LinearSegmentedColormap
import colorsys
import numpy as np
if type not in ('bright', 'soft'):
print ('Please choose "bright" or "soft" for type')
return
if verbose:
print('Number of labels: ' + str(nlabels))
# Generate color map for bright colors, based on hsv
if type == 'bright':
randHSVcolors = [(np.random.uniform(low=0.0, high=1),
np.random.uniform(low=0.2, high=1),
np.random.uniform(low=0.9, high=1)) for i in xrange(nlabels)]
# Convert HSV list to RGB
randRGBcolors = []
for HSVcolor in randHSVcolors:
randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2]))
if first_color_black:
randRGBcolors[0] = [0, 0, 0]
if last_color_black:
randRGBcolors[-1] = [0, 0, 0]
random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
# Generate soft pastel colors, by limiting the RGB spectrum
if type == 'soft':
low = 0.6
high = 0.95
randRGBcolors = [(np.random.uniform(low=low, high=high),
np.random.uniform(low=low, high=high),
np.random.uniform(low=low, high=high)) for i in xrange(nlabels)]
if first_color_black:
randRGBcolors[0] = [0, 0, 0]
if last_color_black:
randRGBcolors[-1] = [0, 0, 0]
random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
# Display colorbar
if verbose:
from matplotlib import colors, colorbar
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1, figsize=(15, 0.5))
bounds = np.linspace(0, nlabels, nlabels + 1)
norm = colors.BoundaryNorm(bounds, nlabels)
cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None,
boundaries=bounds, format='%1i', orientation=u'horizontal')
return random_colormap
## Taken from http://nbviewer.ipython.org/github/bvlc/caffe/blob/master/examples/filter_visualization.ipynb
def tsne(data, label):
model = TSNE(n_components=2, random_state = 0)
print ("tsne preparing..")
data = model.fit_transform(data)
print ("tsne done")
all_lbl = list(set(list(label)))
old2new = dict(zip(all_lbl, range(len(all_lbl))))
new_cmap = rand_cmap(len(all_lbl), verbose=False)
label = np.array([old2new[label[i]] for i in xrange(len(label))])
plt.scatter(data[:,0], data[:,1], cmap=new_cmap, c=label, alpha=0.5, vmin=0, vmax=label.max())
plt.show(block=False)
def tsnei(data_layer, label_layer, nsample):
data = []
lbl = []
num_per_batch = bb(data_layer).shape[0]
totnum = 0
while totnum < nsample:
totnum += num_per_batch
go()
data.append(bb(data_layer))
lbl.append(bb(label_layer))
print ("%d/%d" % (totnum, nsample), end='\\r')
import sys;sys.stdout.flush()
print("")
data = np.concatenate(data)
lbl = np.concatenate(lbl)
tsne(data, lbl)
def cdf(data):
tmp = np.ma.masked_array(data,np.isnan(data))
tmp = tmp.reshape((tmp.size,))
x = np.linspace(tmp.min(), tmp.max())
ecdf = sm.distributions.ECDF(tmp)
y = ecdf(x)
diff_y = - (np.hstack([[0],y]) - np.hstack([y,[0]]))[1:y.size] / (x[1]-x[0])
diff_x = x[1:]
plt.figure()
plt.subplot(1,2,1)
plt.step(x, y)
plt.subplot(1,2,2)
plt.step(diff_x, diff_y)
plt.show(block=False)
def mkarr(data):
data = np.array(data.data).copy().reshape(data.shape)
return data
def show(data, padsize=1, padval=None, defcm=cm.Greys_r):
first = True
if isinstance(data, list):
datalst = data
else:
if len(data.shape)==4:
datalst = [data[i,:,:,:] for i in xrange(data.shape[0])]
else: datalst = [data]
if len(datalst) > 10:
print ("You're now plotting %d images. Continue?(y/N)" % len(datalst))
sure = raw_input()
if sure.strip().lower() != 'y':
return
for data in datalst:
tmp = np.ma.masked_array(data,np.isnan(data))
curmin = tmp.min()
curmax = tmp.max()
curzero = (curmin + curmax) / 2.0
if padval is None: pval = curzero
else: pval = padval
print ("min = %f" % curmin)
print ("max = %f" % curmax)
print ("contains NaN = "+ str(data.max() != curmax))
del tmp
if len(data.shape)==3:
# force the number of filters to be square
n = int(np.ceil(np.sqrt(data.shape[0])))
padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
data = np.pad(data, padding, mode='constant', constant_values=(pval, pval))
# tile the filters into an image
data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
if not first: plt.figure()
plt.imshow(data,interpolation="nearest", cmap=defcm, vmin = data.min(), vmax = data.max())
first = False
plt.show(block=False)
def lslayer(curnet=None):
global net
if curnet is None: curnet = net
for idx in xrange(len(curnet.layers)):
layer_name = curnet._layer_names[idx]
layer_type = curnet.layers[idx].type
layer_blob_num = len(curnet.layers[idx].blobs)
print ("layer[%d]:%s, %s" % (idx, layer_name, layer_type))
for i in xrange(layer_blob_num):
print (" blob[%d]: %s" % (i, str(curnet.layers[idx].blobs[i].data.shape)))
def lsblob(curnet=None):
global net
if curnet is None: curnet = net
for key in net.blobs.keys():
print ("%s : %s" % (key, str(net.blobs[key].data.shape)))
def bb(*kargs):
global net
kargs = list(kargs)
diff = False
if 'diff' in kargs:
kargs.remove('diff')
diff = True
if len(kargs) < 1: raise "See usage by typing hlp()"
if isinstance(kargs[0], caffe._caffe.Net):
curnet = kargs[0]
try: idx1 = kargs[1]
except IndexError: idx1 = None
try: idx2 = kargs[2]
except IndexError: idx2 = None
else:
curnet = net
try: idx1 = kargs[0]
except IndexError: idx1 = None
try: idx2 = kargs[1]
except IndexError: idx2 = None
if not idx2 is None:
if diff: return net.layers[idx1].blobs[idx2].diff
else: return net.layers[idx1].blobs[idx2].data
else:
if diff: return net.blobs[idx1].diff
else: return net.blobs[idx1].data
def dd(*kargs):
kargs=list(kargs)
kargs.append('diff')
return bb(*kargs)
def go(*kargs):
if len(kargs) == 0:
use_net=None
data=None
elif len(kargs) == 1:
if not isinstance(kargs, caffe.Net):
data = kargs[0]
else: use_net = kargs[0]
elif len(kargs) == 2:
use_net = kargs[0]
data = kargs[1]
else:
print ("See usage by typing hlp()")
return
global net
if use_net is None: use_net = net
if not data is None:
pass
use_net.forward()
use_net.backward()
def fg(use_net=None):
global net
if use_net is None: use_net = net
use_net.forward()
def bg(use_net=None):
global net
if use_net is None: use_net = net
use_net.backward()
def bloblst(use_net=None):
global net
if use_net is None: use_net = net
return net.blobs.keys()
def layerlst(curnet=None):
res = []
global net
if curnet is None: curnet = net
for idx in xrange(len(curnet.layers)):
layer_name = curnet._layer_names[idx]
layer_type = curnet.layers[idx].type
layer_blob_num = len(curnet.layers[idx].blobs)
if layer_blob_num > 0:
res.append(idx)
return res
def showrange(data):
first = True
if isinstance(data, list):
datalst = data
else:
datalst = [data]
for data in datalst:
tmp = np.ma.masked_array(data,np.isnan(data))
curmin = tmp.min()
curmax = tmp.max()
print ("min = %15e max=%15e NaN=%s" % (curmin, curmax, str(data.max() != curmax)))
def dbgsgd2(curnet=None):
global net
if curnet is None: curnet = net
for i in curnet.blobs.keys():
print (" == blob[%s]" % (i))
data = curnet.blobs[i].data
tmp = np.ma.masked_array(data,np.isnan(data))
curmin = tmp.min()
curmax = tmp.max()
curmean = tmp.mean()
curstd = tmp.std()
print (" sz: min=%+10e max=%+10e mean=%+10e std=%+10e NaN=%s" % (curmin, curmax, curmean, curstd, str(data.max() != curmax) ))
data = curnet.blobs[i].diff
tmp = np.ma.masked_array(data,np.isnan(data))
curmin = tmp.min()
curmax = tmp.max()
curmean = tmp.mean()
curstd = tmp.std()
print (" grad: min=%+10e max=%+10e mean=%+10e std=%+10e NaN=%s" % (curmin, curmax, curmean, curstd, str(data.max() != curmax) ))
print ("")
def dbgsgd(curnet=None):
global net
if curnet is None: curnet = net
for idx in xrange(len(curnet.layers)):
layer_name = curnet._layer_names[idx]
layer_type = curnet.layers[idx].type
layer_blob_num = len(curnet.layers[idx].blobs)
if layer_blob_num == 0: continue
print ("")
print ("layer[%d]:%s (%s)" % (idx, layer_name, layer_type))
for i in xrange(layer_blob_num):
print (" == blob[%d]" % (i))
data = curnet.layers[idx].blobs[i].data
tmp = np.ma.masked_array(data,np.isnan(data))
curmin = tmp.min()
curmax = tmp.max()
curmean = tmp.mean()
curstd = tmp.std()
print (" sz: min=%+10e max=%+10e mean=%+10e std=%+10e NaN=%s" % (curmin, curmax, curmean, curstd, str(data.max() != curmax) ))
data = curnet.layers[idx].blobs[i].diff
tmp = np.ma.masked_array(data,np.isnan(data))
curmin = tmp.min()
curmax = tmp.max()
curmean = tmp.mean()
curstd = tmp.std()
print (" grad: min=%+10e max=%+10e mean=%+10e std=%+10e NaN=%s" % (curmin, curmax, curmean, curstd, str(data.max() != curmax) ))
def hlp():
print ("* hlp(): show help")
print ("")
print ("* go(net): run 1 iteration")
print ("* fg(net): forward")
print ("* bg(net): backward")
print ("")
print ("* mkarr(blob): make blob into np.array")
print ("* show(data, padsize=1, padval=0): draw 4D-array whose shape is (numch, patch_h, patch_w)")
print ("")
print ("* lslayer(net[default by net]): list all layers")
print ("* lsblob(net[default by net]): list all blobs")
print ("")
print ("* bb(net[default by net], blob_name): returns blob")
print ("* bb(net[default by net], layeridx, blob_name): returns blob associated to layer[layeridx]")
print ("* dd(net[default by net], blob_name): returns diff")
print ("* dd(net[default by net], layeridx, blob_name): returns diff associated to layer[layeridx]")
print ("")
print ("* bloblst(net[default by net]): returns the list of all blob keys")
print ("* layerlst(net[default by net]): returns the list of indices of all layers with weights")
print ("")
print ("* showrange(data): prints range of given matrices")
print ("* dbgsgd(net[default by net]): debug learning rate")
print ("* dbgsgd2(net[default by net]): debug learning rate")
print ("" )
print ("* cdf(data): draw sample cdf function")
"""
def randstr(length):
return ''.join([chr(random.randint(0, 10) + ord('a')) for i in xrange(length)])
def do_extract(args):
import caffe
def ext(fname):
return fname.split('.')[-1].lower()
if len(args)<3:
print ("Usage: [prototxt] [caffemodel] [output file name]")
exit(-1)
fname_prototxt = args[0]
fname_caffemodel = args[1]
fname_output = args[2]
net = caffe.Net(fname_prototxt, fname_caffemodel, caffe.TEST)
layers = net.params.keys()
final = {}
for layer in layers:
if len(net.params[layer]) > 0: final[layer+'_weight'] = net.params[layer][0].data
if len(net.params[layer]) > 1: final[layer+'_bias'] = net.params[layer][1].data
if len(net.params[layer]) > 2:
for i in xrange(2, len(net.params[layer])):
final[layer+'_param_%02d' % i] = net.params[layer][i].data
fname_ext = ext(fname_output)
if fname_ext in ['mat']:
scipy.io.savemat(fname_output, final)
elif fname_ext in ['hdf', 'h5', 'hdf5']:
f = h5py.File(fname_output, 'w')
for key in final.keys():
f[key]=final[key]
f.close()
elif fname_ext in ['cc', 'c', 'cpp']:
print (final.keys())
f = file(fname_output, 'w')
keys = final.keys()
keys.sort()
f.write('// ' + ' '.join(keys) + '\n')
for key in keys:
f.write('extern int XXX_dim;\nextern int XXX_shape[];\nextern float XXX[];\n\n'.replace('XXX', key))
f.write('\n\n')
for key in keys:
f.write('int %s_dim=%d;\n' % (key, len(final[key].shape)))
f.write('int %s_shape[]={%s};\n' % (key, ', '.join([str(x) for x in list(final[key].shape)])))
f.write('float %s[]={' % key)
idx = 0
tmp = final[key].reshape((final[key].size, ))
for idx in xrange(final[key].size):
if idx > 0: f.write(',')
if idx % 25 == 0: f.write('\n')
f.write('%f' % tmp[idx])
f.write('\n};\n\n')
f.close()
def do_clean(args):
os.system("rm -rf ./snapshot/*")
os.system("rm -f ./train.log")
def do_dataset(args):
if len(args) < 1:
print ("Usage: [lmdb path to inspect] [img per row=10] [img per col=10]")
return
import lmdb
import caffe.proto.caffe_pb2
from caffe.proto.caffe_pb2 import Datum
rowsz = 10
colsz = 10
if len(args) > 1: rowsz = int(args[1])
if len(args) > 2: colsz = int(args[2])
env = lmdb.open(args[0], readonly=True)
print ("%d entries" % env.stat()['entries'] )
try:
with env.begin() as txn:
with txn.cursor() as curs:
while True:
stack = []
for key, value in curs:
d = Datum.FromString(value)
c = d.channels
h = d.height
w = d.width
lbl = d.label
im = np.fromstring(d.data, dtype=np.uint8).reshape(c, h, w)
stack.append((key, lbl, im))
if len(stack) == rowsz * colsz:
break
totalim = np.zeros((c, (h+1)*rowsz, (w+1)*colsz))
idx = 0
for key, lbl, im in stack:
x = idx % colsz
y = (idx - x) / colsz
x *= (w+1)
y *= (h+1)
idx += 1
totalim[:, y:y+h, x:x+w] = im
totalim = totalim.transpose(1,2,0) / 255.0
cv2.imshow("img", totalim)
pressed = cv2.waitKey(0)
if pressed == -1 or pressed == 1048603: break
except KeyboardInterrupt:
env.close()
return
env.close()
def do_pltacc(args):
plt.ion()
fname = args[0]
if len(args)>1: recent_entry = int(args[1])
else: recent_entry = None
if len(args)>2: smooth = int(args[2])
else: smooth = None
while True:
f=file(fname, 'r')
lines=f.readlines()
f.close()
iter_indices = []
val = []
idx = 0
for line in lines:
if line.find('Test net') > -1 and line.find('accuracy') > -1:
v = line.strip().split('accuracy = ')[1]
iter_indices.append(float(idx))
val.append(float(v))
idx += 1
y = np.array(val)
x = np.array(iter_indices)
if not recent_entry is None:
y = y[-recent_entry:]
x = x[-recent_entry:]
plt.clf()
plt.plot(x, y)
if not smooth is None:
yy = moving_average(y, smooth)
xx = moving_average(x, smooth)
plt.plot(xx, yy)
plt.pause(2.0)
def moving_average(a, n=3) :
ret = np.cumsum(np.array(a), dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def do_pltmulti(args):
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('x-small')
def draw_acc(fname):
f=file(fname, 'r')
lines=f.readlines()
f.close()
## draw accuracy
iter_indices = []
val = []
idx = 0
for line in lines:
if line.find('Test net') > -1 and line.find('accuracy') > -1:
v = line.strip().split('accuracy = ')[1]
iter_indices.append(float(idx))
val.append(float(v))
idx += 1
y = np.array(val)
x = np.array(iter_indices)
return (x, y)
def draw_loss(fname):
f=file(fname, 'r')
lines=f.readlines()
f.close()
## draw loss
iter_indices = []
val = []
for line in lines:
if line.find('Iteration') > -1 and line.find('loss') > -1:
v = line.strip().split('loss = ')[1]
i = line.strip().split('Iteration ')[1].split(',')[0]
iter_indices.append(float(i))
val.append(float(v))
y = np.array(val)
x = np.array(iter_indices)
return (x, y)
#plt.ion()
fig = plt.gcf()
plt.clf()
plt.subplot(1,2,1)
line_acc=[]
for fname in args:
if os.path.isdir(fname):
fname = os.path.join(fname, 'train.log')
x, y=draw_acc(fname)
p,=plt.plot(x, y, label=fname)
line_acc.append(p)
plt.legend(handles=line_acc, prop=fontP, loc='best')
plt.subplot(1,2,2)
line_loss=[]
for fname in args:
if os.path.isdir(fname):
fname = os.path.join(fname, 'train.log')
x, y=draw_loss(fname)
p,=plt.plot(x, y, label=fname)
line_loss.append(p)
plt.legend(handles=line_loss, prop=fontP, loc='best')
plt.show()
def do_pltloss(args):
plt.ion()
if len(args) == 0: fname = '.'
else: fname = args[0]
if os.path.isdir(fname):
fname = os.path.join(fname, 'train.log')
if len(args)>1: recent_entry = int(args[1])
else: recent_entry = None
if recent_entry == -1: resent_entry = None
if len(args)>2: smooth = int(args[2])
else: smooth = None
if smooth == -1: smooth = None
if len(args)>3: title = args[3]
else: title = "test acc. / trng loss"
while True:
f=file(fname, 'r')
lines=f.readlines()
f.close()
## draw accuracy
iter_indices = []
val = []
idx = 0
for line in lines:
if line.find('Test net') > -1 and line.find('accuracy') > -1:
v = line.strip().split('accuracy = ')[1]
iter_indices.append(float(idx))
val.append(float(v))
idx += 1
y = np.array(val)
x = np.array(iter_indices)
if not recent_entry is None:
y = y[-recent_entry:]
x = x[-recent_entry:]
fig = plt.gcf()
fig.canvas.set_window_title(title)
plt.clf()
plt.subplot(1,2,1)
line1 = plt.plot(x, y)
if not smooth is None:
yy = moving_average(y, smooth)
xx = moving_average(x, smooth)
line2 = plt.plot(xx, yy)
if not smooth is None:
plt.setp(line1, 'color', '#aaaaaa')
plt.setp(line2, 'color', '#ff0000')
## draw loss
iter_indices = []
val = []
for line in lines:
if line.find('Iteration') > -1 and line.find('loss') > -1:
v = line.strip().split('loss = ')[1]
i = line.strip().split('Iteration ')[1].split(',')[0]
iter_indices.append(float(i))
val.append(float(v))
y = np.array(val)
x = np.array(iter_indices)
if not recent_entry is None:
y = y[-recent_entry:]
x = x[-recent_entry:]
plt.subplot(1,2,2)
line1 = plt.plot(x, y)
if not smooth is None:
yy = moving_average(y, smooth)
xx = moving_average(x, smooth)
line2=plt.plot(xx, yy)
if not smooth is None:
plt.setp(line1, 'color', '#aaaaaa')
plt.setp(line2, 'color', '#ff0000')
plt.pause(1.0)
def do_eval(args):
import caffe
caffe.set_mode_gpu()
import openpyxl
if len(args)<2:
print ("arg1=model.prototxt, arg2=model.caffemodel, arg3=output name, arg4=# of test examples(optional), arg5=report(optional), arg6=class_name_list.txt")
return
model_def = args[0]
model_fname = args[1]
output_layer = args[2].strip()
if len(args) > 3: report_path = args[4]
else: report_path = None
net = caffe.Net(model_def, model_fname, caffe.TEST)
print ("loaded..")
class_num = None
if net.blobs.has_key(output_layer):
class_num = net.blobs[output_layer].data.shape[1]
else:
print ("layer %s is not found" % output_layer)
print ("possible layers are: %s" % (', '.join(list(net._blob_names))))
return
if len(args) >= 6:
class_lbl = file(args[5], 'r').readlines()
class_lbl = map(lambda x:x.strip().decode('utf-8'), class_lbl)
class_lbl = filter(lambda x:len(x)>0, class_lbl)
else:
class_lbl = map(lambda x:u'(%d)' % x, range(class_num))
def cls2char(cls):
return class_lbl[int(cls)].encode('utf-8')
def escape_cls2char(cls):
res = ''
for ch in class_lbl[int(cls)]:
res += '&#%d;' % ord(ch)
return res
confusion_matrix = np.zeros([class_num,class_num])
answers = []
answers_by_cls = {}
num_batch=net.blobs['label'].data.size
num_iter=100 if len(args) < 4 else int(float(args[3])/num_batch + 0.999)
for i in xrange(num_iter):
net.forward()
label = list(net.blobs['label'].data.astype(np.int64))
result = list(net.blobs[output_layer].data.argmax(1))
for lbl, out in zip(label, result):
confusion_matrix[lbl, out] += 1.0
for idx in xrange(len(result)):
score_lst = list(net.blobs[output_layer].data[idx].copy())
score_lst = zip(score_lst, range(len(score_lst)))
score_lst.sort()
score_lst.reverse()
score_lst = score_lst[0:5]
ent = (net.blobs['data'].data[idx].astype(np.float), int(label[idx]), int(result[idx]), score_lst)
answers.append(ent)
print ("%d/%d" % (i, num_iter), end='\r')
import sys;sys.stdout.flush()
print ("")
for ent in answers:
img, lbl, res, score_lst = ent
if answers_by_cls.has_key(lbl):
isok = 1 if lbl == res else 0
answers_by_cls[lbl].append((isok, (img, res, score_lst)))
else:
isok = 1 if lbl == res else 0
answers_by_cls[lbl] = [(isok, (img, res, score_lst)),]
for key in answers_by_cls.keys():
entries = answers_by_cls[key]
entries.sort(key=lambda e: e[0])
answers_by_cls[key] = entries
if report_path:
try: os.makedirs(report_path)
except OSError: pass
f = file(os.path.join(report_path, 'index.html'), 'w')
f.write("""
<!DOCTYPE html>
<html>
<frameset cols="25%,*">
<frame src="menu.htm">
<frame name="view">
</frameset>
</html>""")
f.close()
fmenu = file(os.path.join(report_path, 'menu.htm'), 'w')
fmenu.write('<html><head></head><body>')
# Let's do not care about the fucking xlsx file, as we have good mat file
if False:
book = openpyxl.Workbook(encoding="utf-8")
sheet_rc = book.create_sheet(title='raw')
sheet_p = book.create_sheet(title='percent')
#remove default sheet
for sheetname in book.get_sheet_names():
if sheetname in ['raw', 'percent']: continue
s=book.get_sheet_by_name(sheetname)
book.remove_sheet(s)
sheets=[sheet_rc, sheet_p]
for idx in xrange(len(sheets)):
sheets[idx].cell(row=0, column=0).value="Accuracy"
sheets[idx].cell(row=0, column=1).value=np.trace(confusion_matrix) / confusion_matrix.sum() * 100.0
sheets[idx].cell(row=1, column=0).value='GT \\ Output'
for i in xrange(0, class_num):
for idx in xrange(len(sheets)):
sheets[idx].cell(row=1, column=i+1).value='%s(%d)' % ( cls2char(i), i)
sheets[idx].cell(row=i+2, column=0).value='%s(%d)' % ( cls2char(i), i)
tot_cnt = confusion_matrix.sum()
for gt_idx in xrange(0, class_num):
for out_idx in xrange(0, class_num):
sheets[0].cell(row=gt_idx+2, column=out_idx+1).value=confusion_matrix[gt_idx, out_idx]
sheets[1].cell(row=gt_idx+2, column=out_idx+1).value=float(confusion_matrix[gt_idx, out_idx]) / float(tot_cnt)
# freeze panes
sheets[0].freeze_panes = sheets[0].cell('B3')
sheets[1].freeze_panes = sheets[1].cell('B3')
book.save(os.path.join(report_path, 'main.xlsx'))
## save confusion_matrix in a mat file
sp.io.savemat(os.path.join(report_path, 'confusion.mat'), {'confusion': np.array(confusion_matrix)})
## best class pairs to merge
sym = confusion_matrix - np.diag(np.diag(confusion_matrix))
sym = sym + sym.T
conf_lst = []
n = sym.shape[0]
for i in xrange(n):
for j in xrange(i+1, n):
conf_lst.append((sym[i, j], i, j))
conf_lst.sort()
conf_lst.reverse()
fconf=file(os.path.join(report_path, 'confusion.txt'), 'wb')
fconf.write('freq,freq_percent,cls_label1,cls1,cls_label2,cls2,accum_freq,unique_cls\n')
accum_freq = 0
clsset=set()
for freq, i, j in conf_lst:
accum_freq += freq
clsset.add(i)
clsset.add(j)
line = u'%d,%f%%,%s,%d,%s,%d,%d,%d\n' % (freq, 100.0 * float(freq) / float(confusion_matrix.sum()), escape_cls2char(i), i, escape_cls2char(j),j, accum_freq, len(clsset))
if freq == 0: break
fconf.write(line)
fconf.close()
fmenu.write('<a href="./confusion.mat" target="view">Summary</a><br/>\n')
try: os.makedirs(os.path.join(report_path, 'im_f'))
except OSError: pass
try: os.makedirs(os.path.join(report_path, 'im_t'))
except OSError: pass
for cls in answers_by_cls.keys():
fmenu.write('<a href="./cls_%d.html" target="view">%d(%s)</a><br/>\n' % (cls, cls, escape_cls2char(cls)))
idxcnt = 0
idxfname = os.path.join(report_path, 'cls_%d.html' % cls)
idxf = file(idxfname, 'w')
idxf.write('<html><head>')
idxf.write('<style>.item { border:1px solid #000; display:inline-block; width:150px;}\n')
idxf.write('.green { color:#20EE20; font-weight:bold;}\n')
idxf.write('.wrong { color:#EE2020; font-weight:bold;}\n')
idxf.write('</style>')
idxf.write('</head><body>')
idxf.write('<h1>%d(%s)</h1>\n' % (cls, escape_cls2char(cls)))
for isok, data in answers_by_cls[cls]:
img, res, score_lst = data
idxcnt += 1
img -= img.min()
img /= img.max()
img = img[0]
if isok: path_ok = 'im_t'
else: path_ok = 'im_f'
cv2.imwrite(os.path.join(report_path, path_ok,'%05d_%05d.png' % (cls, idxcnt)), img * 255)
if res == cls: anscolor = 'green'
else: anscolor = 'wrong'
top5str = '<br/>\n'.join(['<span style="font-size:0.3em;color:#aaa;">%s-%f</span>' % (escape_cls2char(clsnum), score) for score, clsnum in score_lst])
idxf.write('<div class="item"><img src="./%s/%05d_%05d.png" /><span class="%s">%s</span>(%s)<br/>%s</div>\n' % (path_ok, cls, idxcnt, anscolor, escape_cls2char(res), escape_cls2char(cls), top5str))
idxf.write('</body></html>')
idxf.close()
fmenu.write('</body></html>')
fmenu.close()
f = file(os.path.join(report_path, 'accuracy.txt'), 'w')
f.write("accuracy: %f\n" % (np.trace(confusion_matrix) / confusion_matrix.sum()))
f.close()
print ("accuracy: %f" % (np.trace(confusion_matrix) / confusion_matrix.sum()))
def do_ipython(args):
global CAFFE_ROOT
code = """
import sys
import os
sys.path.append('""" + os.path.join(CAFFE_ROOT, 'python') + """')
import caffe
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
"""
tmpfname = '/tmp/' +randstr(10)
f=file(tmpfname, 'w')
f.write(code)
f.close()
os.system('ipython -i %s' % tmpfname)
os.system('rm -f %s' % tmpfname)
def do_mean(args):
global CAFFE_ROOT
os.system("""
export CAFFE_PATH=\"""" + CAFFE_ROOT + """\"
$CAFFE_PATH./build/tools/compute_image_mean -backend lmdb ./dataset/chinese_train_lmdb ./dataset/chinese_mean.binaryproto
echo "Done."
""")
def do_train(args):
global CAFFE_ROOT
if len(args) > 0: gpuid = args[0]
else: gpuid = "all"
os.system("""
export CAFFE_PATH=\"""" + CAFFE_ROOT + """\"
$CAFFE_PATH/./build/tools/caffe train -gpu %s --solver=solver.prototxt 2>&1 | tee -a train.log
#./learn train ./charconf.ini --solver=solver.prototxt 2>&1 | tee -a train.log
""" % gpuid )
def do_resume(args):
global CAFFE_ROOT
if len(args)<1:
print ("Please specify the .caffemodel or .solverstate file")
return
fname = args[0]
if fname.endswith('.solverstate'):
os.system("""
export CAFFE_PATH=\"""" + CAFFE_ROOT + """\"
$CAFFE_PATH/./build/tools/caffe train --solver solver.prototxt --snapshot %s 2>&1 | tee -a train.log
"""% (fname))
elif fname.endswith('.caffemodel'):
os.system("""
export CAFFE_PATH=\"""" + CAFFE_ROOT + """\"