/
statistics.lua
1583 lines (1428 loc) · 48.5 KB
/
statistics.lua
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
local alternatives = { right=true, left=true, ["two-sided"] = true }
stats = stats or {} -- global environment
stats.running = stats.running or {}
april_set_doc(stats.running,{
class = "namespace",
summary = "Table with running statistics classes",
})
stats.dist = stats.dist or {}
do
local function bisect(dist, x, y, log_p, EPSILON, MAX)
local i,m = 0,nil
repeat
m = 0.5 * (x + y)
local aux = dist:logcdf(matrix(1,1,{m}))[1]
if (y-x < EPSILON) or math.abs(aux - log_p) < EPSILON then
return m
elseif aux > log_p then
y = m
else
x = m
end
i=i+1
until i == MAX
fprintf(io.stderr, "Warning!!! bisect maximum number of iterations\n")
return m
end
stats.dist.quantile = function(dist, p, EPSILON, MAX)
assert(dist:size() == 1, "Only implemented for univariate distributions")
assert(0 < p and p < 1.0, "The probabilbity should be in range (0,1)")
local log_p = math.log(p)
local a = -1.0
local b = 1.0
while true do
local cdfa = dist:logcdf(matrix(1,1,{a}))[1]
local cdfb = dist:logcdf(matrix(1,1,{b}))[1]
if cdfa < log_p and cdfb > log_p then break end
if cdfa > log_p then a = a*10 end
if cdfb < log_p then b = b*10 end
end
return bisect(dist, a, b, log_p, EPSILON or 1e-08, MAX or 10000)
end
end
local tbl,methods = class("stats.hypothesis_test")
april_set_doc(tbl, {
class = "class",
summary = "Result of hypotheses test",
})
stats.hypothesis_test = tbl
tbl.constructor =
april_doc{
class = "method",
summary = "Constructor given a pivot and the H0 stats.dist instance",
} ..
function(self, pivot, h0_dist, true_dist)
assert(pivot and h0_dist and true_dist,
"Needs a pivot, H0 distribution and true distribution")
self.P = matrix(1,1,{pivot})
self.h0_dist = h0_dist
self.true_dist = true_dist
end
methods.pvalue =
april_doc{
class = "method",
summary = "Returns the p-value of the pivot for the H0 distribution",
} ..
function(self, alternative)
local alternative = alternative or "two-sided"
april_assert(alternatives[alternative],
"Unknown alternative value %s", alternative)
local P = self.P
local h0_dist = self.h0_dist
local a,b = 0.0,0.0
local two_sided = (alternative=="two-sided")
if two_sided or alternative == "left" then
a = math.exp( h0_dist:logcdf(-P)[1] )
if two_sided and a > 0.5 then a = 1.0 - a end
end
if two_sided or alternative == "right" then
b = 1.0 - math.exp( h0_dist:logcdf(P)[1] )
if two_sided and b > 0.5 then b = 1.0 - b end
end
return a + b
end
methods.pivot =
april_doc{
class = "method",
summary = "Returns the test pivot",
} ..
function(self) return self.P:get(1,1) end
methods.ci =
april_doc {
class = "method",
summary = "Returns the confidence interval of the true distribution",
} ..
function(self, confidence, alternative)
local alternative = alternative or "two-sided"
april_assert(alternatives[alternative],
"Unknown alternative value %s", alternative)
local true_dist = self.true_dist
local alpha = 1.0 - (confidence or 0.95)
local two_sided = (alternative=="two-sided")
if two_sided then alpha = alpha * 0.5 end
local a = -math.huge
local b = math.huge
if two_sided or alternative == "right" then
a = stats.dist.quantile(true_dist, alpha)
end
if two_sided or alternative == "left" then
b = stats.dist.quantile(true_dist, 1.0 - alpha)
end
return a,b
end
class.extend_metamethod(tbl, "__tostring", function(self)
local a,b = self:ci(0.95)
local tbl = {
"pivot= ", tostring(self:pivot()),
"\np-value= ", tostring(self:pvalue()),
"\nCI(95%)= [", tostring(a), ", ", tostring(b), "]" }
return table.concat(tbl)
end)
-----------------------------------------------------------------------------
local mop = matrix.op
local sdiag = matrix.sparse.diag
-- x must be a 2D matrix
local function center(x,mu)
local x_dim = x:dim()
local N = x_dim[1]
if #x_dim == 1 then
mu = mu or x:sum()/N
return x - mu, mu
else
mu = mu or x:sum(1):scal(1/N)
return matrix.ext.broadcast(bind(x.axpy, nil, -1.0), x, mu), mu
end
end
stats.standardize =
april_doc{
class = "function",
summary = "Standardize data to have zero-mean one-variance",
description = "Data is ordered by rows, features by columns.",
params = { "A 2D matrix", "A table with center and/or scale matrices [optional]"},
outputs = { "Another new allocated matrix", "Center matrix", "Scale matrix" },
} ..
function(x, params)
local params = params or {}
assert(#x:dim() == 2, "Needs a 2D matrix")
local N = x:dim(1)
local mu,sigma = params.center,params.scale
if not sigma then
local sigma2,mup = stats.var(x,1)
mu = mu or mup
sigma = sigma2:sqrt()
elseif not mu then
mu = stats.amean(x,1)
end
local x = matrix.ext.broadcast(bind(x.axpy, nil, -1.0), x, mu)
x = matrix.ext.broadcast(x.cmul, x, 1/sigma)
return x,mu,sigma
end
stats.center =
april_doc{
class = "function",
summary = "Centers data by rows, computing mean of every column",
description = "Data is ordered by rows, features by columns.",
params = { "A 2D matrix", "Center matrix" },
outputs = { "Another new allocated matrix", "The center matrix" },
} ..
function(x,mu)
assert(#x:dim() == 2, "Needs a 2D matrix")
return center(x,mu)
end
stats.var =
april_doc{
class = "function",
summary = "Computes variance over a dimension",
params = { "A matrix",
"A dimension number [optional].", },
outputs = {
"A new allocated matrix or a number if not dim given",
"The mean used to center the data"
},
} ..
function(x,dim)
local mean = stats.amean(x,dim)
local x,x_row,sz = x:clone()
if dim then
sz = x:dim(dim)
for i=1,sz do x_row=x:select(dim,i,x_row):axpy(-1.0, mean) end
else
x:scalar_add(-mean)
sz = x:size()
end
return x:pow(2):sum(dim)/(sz-1),mean
end
stats.std =
april_doc{
class = "function",
summary = "Computes standard deviation over a dimension",
params = { "A matrix",
"A dimension number [optional].", },
outputs = {
"A new allocated matrix or a number if not dim given",
"The mean used to center the data",
},
} ..
function(x,dim)
local result,center = stats.var(x,dim)
if dim then result:sqrt()
else result = math.sqrt(result)
end
return result,center
end
stats.cov =
april_doc{
class = "function",
summary = "Compute covariance matrix of two matrices.",
description = "Data is ordered by rows, features by columns.",
params = {
"A 2D matrix or a vector (x)",
"Another 2D matrix or a vector (y)",
"An [optional] table with 'centered' boolean, 'true_mean' boolean",
},
outputs = { "Covariance matrix" }
} ..
april_doc{
class = "function",
summary = "Compute covariance matrix.",
description = "Data is ordered by rows, features by columns.",
params = {
"A 2D matrix or a vector (x)",
"An [optional] table with 'centered' boolean, 'true_mean' boolean",
},
outputs = { "Covariance matrix",
"The x center vector if not centered flag [optional]",
"The y center vector if not centered flag [optional]" }
} ..
function(x,...)
local y,params = ...
if type(y) == "table" or not y then y,params = x,y end
collectgarbage("collect")
assert(class.is_a(x,matrix) and class.is_a(y,matrix),
"Needs at least two matrix arguments")
local params = get_table_fields(
{
centered = { type_match = "boolean", default = nil },
true_mean = { type_match = "boolean", default =nil },
}, params)
assert(not params.true_mean or params.centered,
"true_mean=true is mandatory of centered=true")
local x_dim,y_dim = x:dim(),y:dim()
assert((#x_dim <= 2) and (#y_dim <= 2), "Needs 2D matrices or vectors")
assert(x_dim[1] == y_dim[1] and x_dim[2] == y_dim[2],
"Require same shape matrices")
local mu_x,mu_y
local N,M = table.unpack(x_dim)
if not params.centered then
local oldx = x
x,mu_x = center(x)
if rawequal(xold,y) then y,mu_y = x,mu_x else y,mu_y = center(y) end
end
local sz = N-1
if params.true_mean then sz = N end
return (x:transpose() * y):scal(1/sz):rewrap(M or 1,M or 1),mu_x,mu_y
end
stats.cor =
april_doc{
class = "function",
summary = "Compute correlation matrix of two matrices.",
description = "Data is ordered by rows, features by columns.",
params = {
"A 2D matrix or a vector (x)",
"Another 2D matrix or a vector (y)",
"An [optional] table with 'centered' boolean",
},
outputs = { "Correlation matrix" }
} ..
april_doc{
class = "function",
summary = "Compute correlation matrix.",
description = "Data is ordered by rows, features by columns.",
params = {
"A 2D matrix or a vector (x)",
"An [optional] table with 'centered' boolean",
},
outputs = { "Correlation matrix",
"The x center vector if not centered flag [optional]",
"The y center vector if not centered flag [optional]" }
} ..
function(x,...)
local y,params = ...
if type(y) == "table" or not y then y,params = x,y end
local params = params or {}
local mu_x,mu_y
if not params.centered then
local xold = x
x,mu_x = center(x)
if rawequal(xold,y) then y,mu_y = x,mu_x else y,mu_y = center(y) end
end
local function cstd(m) return sdiag((m^2):sum(1):scal(1/(m:dim(1)-1)):sqrt():div(1):squeeze()) end
local sigma = stats.cov(x,y,{ centered=true })
local sx = cstd(x)
local sy = rawequal(x,y) and sx or cstd(y)
return sx * sigma * sy,mu_x,mu_y
end
stats.acf =
april_doc{
class = "function",
summary = "Compute auto-correlation of one or more series.",
description = "Data is ordered by rows, series by columns.",
params = {
"A 2D matrix or a vector (x)",
{ "An [optional] table with 'lag_max' number,",
"'lag_step' number, 'lag_start' number,",
"'cor' function (one of stats.cor [default], stats.cov)." },
},
outputs = { "A matrix with auto-correlation of the series",
"A matrixInt32 with lag values" },
} ..
function(x,params)
assert(class.is_a(x, matrix), "Needs a matrix argument")
local x_dim = x:dim()
assert(x_dim[1] > 1, "Needs two or more rows")
assert(#x_dim <= 2, "Requires 2D matrix or a vector")
local params = get_table_fields(
{
lag_max = { type_match = "number", default = x_dim[1]-2 },
lag_step = { type_match = "number", default = 1 },
lag_start = { type_match = "number", default = 1 },
cor = { type_match = "function", default = stats.cor },
}, params)
local lag_start,lag_max,lag_step = params.lag_start,params.lag_max,params.lag_step
if #x_dim == 1 then x = x:rewrap(x:size(),1) end
local N,M = x_dim[1],x:dim(2)
local result = matrix(math.floor((lag_max + 1 - lag_start) / lag_step), M)
local acf_func = params.cor
for j=1,M do
local i=1
for lag = lag_start, lag_max, lag_step do
local a,b = x({1,N-lag},j), x({lag+1,N},j)
local y = acf_func(a,b)
result[{i,j}] = y
i=i+1
end
end
local lags = matrixInt32(iterator(range(lag_start,lag_max,lag_step)):table())
return result,lags
end
-- arithmetic mean of a matrix
stats.amean =
april_doc{
class = "function",
summary = "Computes the arithmetic mean over a given dimension",
params = {
"A matrix",
"A dimension number [optional]",
},
outputs = {
"A matrix if given a dimension, a number otherwise",
},
} ..
function(m, D)
local r = m:sum(D)
if D then
return r:scal(1/m:dim(D))
else
return r/m:size()
end
end
-- geometric mean of a matrix with positive elements
stats.gmean =
april_doc{
class = "function",
summary = "Computes the geometric mean over a given dimension",
params = {
"A matrix with positive elements",
"A dimension number [optional]",
},
outputs = {
"A matrix if given a dimension, a number otherwise",
},
} ..
function(m, D)
local r = mop.log(m):sum(D)
if D then
return r:scal(1.0/m:dim(D)):exp()
else
return math.exp(r / m:size())
end
end
-- harmonic mean of a matrix with non-zero elements
stats.hmean =
april_doc{
class = "function",
summary = "Computes the harmonic mean over a given dimension",
params = {
"A matrix with non-zero elements",
"A dimension number [optional]",
},
outputs = {
"A matrix if given a dimension, a number otherwise",
},
} ..
function(m, D)
local r = (1 / m):sum(D)
if D then
return r:div( m:dim(D) )
else
return m:size() / r
end
end
-----------------------------------------------------------------------------
local mean_var,mean_var_methods = class("stats.running.mean_var")
stats.running.mean_var = mean_var -- global environment
april_set_doc(stats.running.mean_var, {
class = "class",
summary = "Class to compute mean and variance",
description ={
"This class is designed to compute mean and variance",
"by adding a sequence of data values (or tables)",
}, })
-----------------------------------------------------------------------------
april_set_doc(stats.running.mean_var, {
class = "method", summary = "Constructor",
description ={
"Constructor of a mean_var object",
},
params = {
"A number [optional]. If given, the assumed_mean approach",
"will be followed.",
},
outputs = { "A mean_var object" }, })
function mean_var:constructor()
self:clear()
end
-----------------------------------------------------------------------------
mean_var_methods.clear =
april_doc{
class = "method",
summary = "Re-initializes the object"
} ..
function(self)
self.old_m = 0
self.old_s = 0
self.new_m = 0
self.new_s = 0
self.N = 0
return self
end
-----------------------------------------------------------------------------
mean_var_methods.add =
april_doc{
class = "method", summary = "Adds one value",
params = {
"A number",
},
outputs = { "The caller mean_var object (itself)" },
} ..
april_doc{
class = "method", summary = "Adds a sequence of values",
params = {
"A Lua table (as array of numbers)",
},
outputs = { "The caller mean_var object (itself)" },
} ..
april_doc{
class = "method",
summary = "Adds a sequence of values from an iterator function",
params = {
"An iterator function",
},
outputs = { "The caller mean_var object (itself)" },
} ..
function (self, ...)
local arg = { ... }
local v = arg[1]
if type(v) == "table" then
return self:add(ipairs(v))
elseif type(v) == "function" then
local f,s,v = table.unpack(arg)
local tmp = table.pack(f(s,v))
while tmp[1] ~= nil do
v = tmp[1]
if #tmp > 1 then table.remove(tmp,1) end
for _,aux in ipairs(tmp) do self:add(aux) end
tmp = table.pack(f(s,v))
end
elseif type(v) == "number" then
self.N = self.N + 1
-- see Knuth TAOCP vol 2, 3rd edition, page 232
if self.N == 1 then
self.old_m,self.new_m = v,v
self.old_s = 0.0
else
local old_diff = (v - self.old_m)
self.new_m = self.old_m + old_diff/self.N
self.new_s = self.old_s + old_diff*(v - self.new_m)
-- setup for next iteration
self.old_m = self.new_m
self.old_s = self.new_s
end
else
error("Incorrect type="..type(v)..". Expected number, table or function")
end
return self
end
-----------------------------------------------------------------------------
mean_var_methods.size =
april_doc{
class = "method",
summary = "Return the number of elements added",
outputs = { "The number of elements added" },
} ..
function(self)
return self.N
end
-----------------------------------------------------------------------------
mean_var_methods.compute =
april_doc{
class = "method",
summary = "Computes mean and variance of given values",
outputs = {
"A number, the mean of the data",
"A number, the variance of the data",
},
} ..
function(self)
return self.new_m,self.new_s/(self.N-1)
end
--------------------
-- Confusion Matrix
-- -----------------
local confus_matrix,confus_matrix_methods = class("stats.confusion_matrix")
stats.confusion_matrix = confus_matrix -- global environment
april_set_doc(stats.confusion_matrix, {
class = "class",
summary = "class for computing confusion matrix and classification metrics",
description ={
"This class is designed to store a confusion matrix and compute main metrics for classification stats",
},
})
april_set_doc(stats.confusion_matrix, {
class ="method",
summary = "Constructor of confusion matrix.",
description ={
"This class is designed to store a confusion matrix and compute main metrics for classification stats",
},
params = {
"A number of classes [mandatory].",
"A table of size num_classes, with the elements on the set.",
outputs = {"A confusion_matrix object"}
}
})
function confus_matrix:constructor(num_classes, class_dict)
local confusion = {}
for i = 1, num_classes do
local t = {}
for j = 1, num_classes do
table.insert(t, 0)
end
table.insert(confusion, t)
end
if (class_dict) then
--assert(#class_dict == num_classes, "The map table doesn't have the exact size")
map_dict = class_dict
--for i, v in ipairs(map_table) do
-- map_dict[v] = i
--end
end
self.num_classes = num_classes
self.confusion = confusion
self.hits = 0
self.misses = 0
self.samples = 0
-- FIXME: IS NOT POSSIBLE USE MAP DICT AS NIL
self.map_dict = map_dict or false
end
confus_matrix_methods.clone =
april_doc{
class ="method",
summary = "Clone onstructor of confusion matrix.",
description ={
"This class is designed to store a confusion matrix and compute main metrics for classification stats",
},
params = {
}
} ..
function(self)
local obj = table.deep_copy(self)
return class_instance(obj, stats.confusion_matrix)
end
confus_matrix_methods.reset =
april_doc{
class = "method", summary = "Reset to 0 all the counters",
} ..
function(self)
for i = 1, self.num_classes do
local t = {}
for j = 1, self.num_classes do
self.confusion[i][j] = 0
end
end
self.hits = 0
self.misses = 0
self.samples = 0
end
function confus_matrix_methods:checkType(clase)
return type(clase) == "number" and clase >= 1 and clase <= self.num_classes or false
end
---------------------------------------------
function confus_matrix_methods:addSample(pred, gt)
if self.map_dict then
pred = map_dict[pred]
gt = map_dict[gt]
end
if not self:checkType(pred) or not self:checkType(gt) then
printf("Error %f %f, %d\n", pred, gt, self.samples)
return
--error("The class is not correct")
end
if gt == pred then
self.hits = self.hits + 1
else
self.misses = self.misses + 1
end
self.samples = self.samples + 1
self.confusion[gt][pred] = self.confusion[gt][pred] + 1
end
------------------------------------------------
confus_matrix_methods.printConfusionRaw =
april_doc{
class = "method", summary = "Print the counters for each class",
} ..
function(self)
for i,v in ipairs(self.confusion) do
print(table.concat(v, "\t"))
end
end
confus_matrix_methods.printConfusion =
april_doc{
class = "method", summary = "Print the counters for each class and PR and RC",
params = { "A num_classes string table [optional] with the tags of each class",}
} ..
function(self, tags)
local total_pred = {}
printf("\t|\t Predicted ")
for i = 1, self.num_classes do
printf("\t\t")
end
printf("|\n")
printf("______\t|")
for i = 1, self.num_classes do
printf("\t___\t")
end
printf("\t___\t\t|\n")
for i,v in ipairs(self.confusion) do
local tag = i
if tags then
tag = tags[i]
end
printf("%s\t|\t", tag)
local recall, hits, total = self:getRecall(i)
printf("%s\t|\t %d/%d %0.4f\t|\n", table.concat(v, "\t|\t"), hits, total, recall)
end
printf("______\t|")
for i = 1, self.num_classes do
printf("\t___\t")
end
printf("\t___\t|\n")
printf("\t\t|")
for i = 1, self.num_classes do
printf("\t%0.4f\t|", self:getPrecision(i))
end
local acc, hits, total = self:getAccuracy()
printf("\t%d/%d %0.4f\t|\n", hits, total, acc)
end
confus_matrix_methods.tostring =
function(self)
local total_pred = {}
local t = {}
table.insert(t, "\t|\t Predicted ")
for i = 1, self.num_classes do
table.insert(t, ("\t\t"))
end
table.insert(t,"|\n")
table.insert(t, "______\t|")
for i = 1, self.num_classes do
table.insert(t, "\t___\t")
end
table.insert(t, "\t___\t\t|\n")
for i,v in ipairs(self.confusion) do
local tag = i
table.insert(t, string.format("%s\t|\t", tag))
local recall, hits, total = self:getRecall(i)
table.insert(t, string.format("%s\t|\t %d/%d %0.4f\t|\n", table.concat(v, "\t|\t"), hits, total, recall))
end
table.insert(t, "______\t|")
for i = 1, self.num_classes do
table.insert(t, "\t___\t")
end
table.insert(t, "\t___\t|\n")
table.insert(t, "\t\t|")
for i = 1, self.num_classes do
table.insert(t, string.format("\t%0.4f\t|", self:getPrecision(i)))
end
local acc, hits, total = self:getAccuracy()
table.insert(t, string.format("\t%d/%d %0.4f\t|\n", hits, total, acc))
return table.concat(t,"")
end
function confus_matrix_methods:printInf()
printf("Samples %d, hits = %d, misses = %d (%0.4f)\n", self.samples, self.hits, self.misses, self.misses/self.total)
for i = 1, self.num_classes do
print("Predicted %d", i)
local total = 0
for j = 1, self.num_classes do
total = total + self.confusion[i][j]
end
for j = 1, self.num_classes do
printf(" - class %d %d/%d (%0.4f)", j, self.confusion[i][j], total, self.confusion[i][j]/total)
end
print()
end
end
--------------------------------------------
-- Datasets and Tables Iterators
--------------------------------------------
function stats.confusion_matrix.twoTablesIterator(table_pred, table_gt)
local i = 0
local n = #table_pred
return function()
i = i+1
if i <= n then return table_pred[i],table_gt[i] end
end
end
----------------------------------------------------------------
function stats.confusion_matrix.oneTableIterator(typeTable)
local i = 0
local n = #typeTable
return function()
i = i+1
if i <= n then return typeTable[i][1], typeTable[i][2] end
end
end
--------------------------------------------------------------
function stats.confusion_matrix.oneDatasetIterator(typeDataset)
local i = 0
local n = typeDataset:numPatterns()
return function()
i = i+1
if i <= n then return typeDataset:getPattern(i)[1], typeDataset:getPattern(i)[2] end
end
end
function stats.confusion_matrix.twoDatasetsIterator(predDs, gtDs)
local i = 0
assert(predDs:numPatterns() == gtDs:numPatterns(), "Datasets doesn't have the same size")
local n = predDs:numPatterns()
return function()
i = i+1
if i <= n then return predDs:getPattern(i)[1], gtDs:getPattern(i)[1] end
end
end
---------------------------------------------------------------------------------------------------------
confus_matrix_methods.addData =
april_doc{
class = "method",
summary = "Add the info of Predicted and Ground Truth set",
description = {
"This class recieves two tables with the predicted class and the",
"ground truth of that class.",
"Also it can recieve a iterator function that returns two elements:",
"predicted sample and groundtruth sample"
},
params = {
"This parameter can be a table of the predicted tags or an iterator function",
"This parameter is used if the first parameter is the Predicted table, otherwise it should be nil"},
} ..
function(self, param1, param2)
local iterator
if( type(param1) == 'function') then
iterator = param1
assert(param2 == nil)
elseif (type(param1) == 'dataset') then
iterator = stats.confusion_matrix.twoDatasetsIterator(param1, param2)
else
iterator = stats.confusion_matrix.twoTablesIterator(param1, param2)
assert(type(param1) == "table" and type(param2) == "table", "The type of the params is not correct")
assert(#param1, #param2, "The tables does not have the same dimension")
end
for pred, gt in iterator do
self:addSample(pred, gt)
end
end
---------------------------------------------------------------
confus_matrix_methods.getError =
april_doc{
class = "method", summary = "Return the global classification error (misses/total)",
outputs = { "The global classification error." },
} ..
function(self)
return self.misses/self.samples, self.misses, self.samples
end
confus_matrix_methods.getWeightedError =
april_doc{
class = "method", summary = "Return the classification error weighted by given values",
params = {"A table of size weight"},
outputs = { "The global classification error." },
} ..
function(self, weights)
local totalError = 0.0
for i,w in ipairs(weights) do
totalError = totalError+(1-w*self:getRecall(i))
end
return totalError
end
confus_matrix_methods.getAvgError =
april_doc{
class = "method", summary = "Return the average error.",
outputs = { "The average classification error." },
} ..
function(self, weights)
local totalError = 0.0
local w = 1.0/self.num_classes
local i
for i = 1, self.num_classes do
totalError = totalError+(1-self:getRecall(i))
end
return totalError*w
end
confus_matrix_methods.getAccuracy =
april_doc{
class = "method", summary = "Return the accuracy (hits/total)",
outputs = { "The global accuracy." },
} ..
function(self)
return self.hits/self.samples, self.hits, self.samples
end
--------------------------------------------------------------
function confus_matrix_methods:getConfusionTables()
return self.confusion
end
------------------------------------------------------------
--
confus_matrix_methods.getPrecision =
april_doc{
class = "method", summary = "Return the accuracy (hits/total)",
params = {"The index of the class for computing the Precision"},
outputs = { "The selected class Precision." },
} ..
function(self, tipo)
local tp = 0
local den = 0
-- Moving by columns
for i=1, self.num_classes do
v = self.confusion[i][tipo]
if i == tipo then
tp = v
end
den = den + v
end
if den == 0 then
return 0, tp, den
end
return tp/den, tp, den
end
confus_matrix_methods.getRecall =
april_doc{
class = "method", summary = "Return the accuracy (hits/total)",
params = {"The index of the class for computing the Recall"},
outputs = { "The selected class Recall." },
} ..
function(self, tipo)
local tp = 0
local den = 0
-- Moving by columns
for j=1, self.num_classes do
v = self.confusion[tipo][j]
if j == tipo then
tp = v
end
den = den + v
end
if den == 0 then
return 0, tp, den
end
return tp/den, tp, den
end
confus_matrix_methods.getFMeasure =
april_doc{