File Coverage

blib/lib/AI/ConfusionMatrix.pm
Criterion Covered Total %
statement 77 77 100.0
branch 14 16 87.5
condition n/a
subroutine 8 8 100.0
pod 1 1 100.0
total 100 102 98.0


line stmt bran cond sub pod time code
1             package AI::ConfusionMatrix;
2             $AI::ConfusionMatrix::VERSION = '0.007';
3 1     1   53525 use strict;
  1         3  
  1         23  
4 1     1   4 use warnings;
  1         2  
  1         19  
5 1     1   4 use Carp;
  1         1  
  1         52  
6 1     1   5 use Exporter 'import';
  1         2  
  1         86  
7             our @EXPORT= qw (makeConfusionMatrix);
8 1     1   6 use strict;
  1         8  
  1         60  
9 1     1   664 use Tie::File;
  1         15783  
  1         607  
10              
11             # ABSTRACT: Make a confusion matrix
12              
13             sub makeConfusionMatrix {
14 2     2 1 3620 my ($matrix, $file, $delem) = @_;
15 2 100       7 unless(defined $delem) {
16 1         3 $delem = ',';
17             }
18              
19 2 50       6 carp ('First argument must be a hash reference') if ref($matrix) ne 'HASH';
20 2 50       12 tie my @array, 'Tie::File', $file or carp "$!";
21 2         229 my $n = 1;
22 2         2 my @columns;
23 2         3 my @expected = sort keys %{$matrix};
  2         9  
24 2         5 my %stats;
25             my %totals;
26 2         4 for my $expected (@expected) {
27 6         25 $array[$n] = $expected;
28 6         1834 ++$n;
29 6         11 $stats{$expected}{'fn'} = 0;
30 6         10 $stats{$expected}{'tp'} = 0;
31             # Ensure that the False Positive counter is defined to be able to compute the total later
32 6 100       13 unless(defined $stats{$expected}{'fp'}) {
33 4         6 $stats{$expected}{'fp'} = 0;
34             }
35 6         6 for my $predicted (keys %{$matrix->{$expected}}) {
  6         40  
36 14         22 $stats{$expected}{'total'} += $matrix->{$expected}->{$predicted};
37 14 100       32 $stats{$expected}{'tp'} += $matrix->{$expected}->{$predicted} if $expected == $predicted;
38 14 100       21 if ($expected != $predicted) {
39 8         9 $stats{$expected}{'fn'} += $matrix->{$expected}->{$predicted};
40 8         13 $stats{$predicted}{'fp'} += $matrix->{$expected}->{$predicted};
41             }
42 14         27 $totals{$predicted} += $matrix->{$expected}->{$predicted};
43             # Add the label to the array of columns if it does not contain it already
44 14 100       27 push @columns, $predicted unless _findIndex($predicted, \@columns);
45             }
46              
47 6         44 $stats{$expected}{'acc'} = sprintf("%.2f%%", ($stats{$expected}{'tp'} * 100) / $stats{$expected}{'total'});
48             }
49              
50 2         4 for my $expected (@expected) {
51 6         9 $totals{'total'} += $stats{$expected}{'total'};
52 6         6 $totals{'tp'} += $stats{$expected}{'tp'};
53 6         9 $totals{'fn'} += $stats{$expected}{'fn'};
54 6         7 $totals{'fp'} += $stats{$expected}{'fp'};
55 6         21 $stats{$expected}{'sensitivity'} = sprintf("%.2f%%", (($stats{$expected}{'tp'} * 100) / ($stats{$expected}{'tp'} + $stats{$expected}{'fp'})));
56             }
57              
58 2         8 $totals{'acc'} = sprintf("%.2f%%", ($totals{'tp'} * 100) / $totals{'total'});
59 2         16 $totals{'sensitivity'} = sprintf("%.2f%%", ($totals{'tp'} * 100) / ($totals{'tp'} + $totals{'fp'}));
60 2         7 @columns = sort @columns;
61 2         8 map {$array[0] .= $delem . $_} join $delem, (@columns, 'TOTAL', 'TP', 'FP', 'FN', 'SENS', 'ACC');
  2         9  
62 2         680 $n = 1;
63 2         5 for my $expected (@expected) {
64 6         8 my $lastIndex = 0;
65 6         7 my $index;
66 6         7 for my $predicted (sort keys %{$matrix->{$expected}}) {
  6         20  
67             # Calculate the index of the label in the array of columns
68 14         29 $index = _findIndex($predicted, \@columns);
69             # Print some of the delimiter to get to the column of the next value predicted
70 14         54 $array[$n] .= $delem x ($index - $lastIndex) . $matrix->{$expected}{$predicted};
71 14         3453 $lastIndex = $index;
72             }
73              
74             # Get to the columns of the stats
75 6         24 $array[$n] .= $delem x (scalar(@columns) - $lastIndex + 1);
76             $array[$n] .= join $delem, (
77             $stats{$expected}{'total'},
78             $stats{$expected}{'tp'},
79             $stats{$expected}{'fp'},
80             $stats{$expected}{'fn'},
81             $stats{$expected}{'sensitivity'},
82 6         1395 $stats{$expected}{'acc'}
83             );
84 6         1401 ++$n;
85             }
86             # Print the TOTAL row to the csv file
87 2         8 $array[$n] = 'TOTAL' . $delem;
88 2         536 map {$array[$n] .= $totals{$_} . $delem} (sort keys %totals)[0 .. $#columns];
  10         2086  
89 2         517 $array[$n] .= join $delem, ($totals{'total'}, $totals{'tp'}, $totals{'fp'}, $totals{'fn'}, $totals{'sensitivity'}, $totals{'acc'});
90              
91 2         466 untie @array;
92             }
93              
94             sub _findIndex {
95 28     28   41 my ($string, $array) = @_;
96 28         51 for (0 .. @$array - 1) {
97 76 100       77 return $_ + 1 if ($string eq @{$array}[$_]);
  76         143  
98             }
99             }
100              
101             =head1 NAME
102              
103             AI::ConfusionMatrix - make a confusion matrix
104              
105             =head1 SYNOPSIS
106              
107             my %matrix;
108              
109             Loop over your tests
110              
111             ---
112              
113             $matrix{$expected}{$predicted} += 1;
114              
115             ---
116              
117             makeConfusionMatrix(\%matrix, 'output.csv');
118              
119              
120             =head1 DESCRIPTION
121              
122             This module prints a L from a hash reference. This module tries to be generic enough to be used within a lot of machine learning projects.
123              
124             =head3 Function
125              
126             =head4 C
127              
128             This function makes a confusion matrix from C<$hash_ref> and writes it to C<$file>. C<$file> can be a filename or a file handle opened with the C mode. If C<$delimiter> is present, it is used as a custom separator for the fields in the confusion matrix.
129              
130             Examples:
131              
132             makeConfusionMatrix(\%matrix, 'output.csv');
133             makeConfusionMatrix(\%matrix, 'output.csv', ';');
134             makeConfusionMatrix(\%matrix, *$fh);
135              
136             The hash reference must look like this :
137              
138             $VAR1 = {
139              
140              
141             'value_expected1' => {
142             'value_predicted1' => value
143             },
144             'value_expected2' => {
145             'value_predicted1' => value,
146             'value_predicted2' => value
147             },
148             'value_expected3' => {
149             'value_predicted3' => value
150             }
151              
152             };
153              
154             The output will be in CSV. Here is an example:
155              
156             ,1974,1978,2002,2003,2005,TOTAL,TP,FP,FN,SENS,ACC
157             1974,3,1,,,2,6,3,4,3,42.86%,50.00%
158             1978,1,5,,,,6,5,4,1,55.56%,83.33%
159             2002,2,2,8,,,12,8,1,4,88.89%,66.67%
160             2003,1,,,7,2,10,7,0,3,100.00%,70.00%
161             2005,,1,1,,6,8,6,4,2,60.00%,75.00%
162             TOTAL,7,9,9,7,10,42,29,13,13,69.05%,69.05%
163              
164             Prettified:
165              
166             | | 1974 | 1978 | 2002 | 2003 | 2005 | TOTAL | TP | FP | FN | SENS | ACC |
167             |-------|------|------|------|------|------|-------|----|----|----|---------|--------|
168             | 1974 | 3 | 1 | | | 2 | 6 | 3 | 4 | 3 | 42.86% | 50.00% |
169             | 1978 | 1 | 5 | | | | 6 | 5 | 4 | 1 | 55.56% | 83.33% |
170             | 2002 | 2 | 2 | 8 | | | 12 | 8 | 1 | 4 | 88.89% | 66.67% |
171             | 2003 | 1 | | | 7 | 2 | 10 | 7 | 0 | 3 | 100.00% | 70.00% |
172             | 2005 | | 1 | 1 | | 6 | 8 | 6 | 4 | 2 | 60.00% | 75.00% |
173             | TOTAL | 7 | 9 | 9 | 7 | 10 | 42 | 29 | 13 | 13 | 69.05% | 69.05% |
174              
175             =over
176              
177             =item TP:
178              
179             True Positive
180              
181             =item FP:
182              
183             False Positive
184              
185             =item FN:
186              
187             False Negative
188              
189             =item SENS
190              
191             Sensitivity. Number of true positives divided by the number of positives.
192              
193             =item ACC:
194              
195             Accuracy
196              
197             =back
198              
199             =head1 AUTHOR
200              
201             Vincent Lequertier
202              
203             =head1 LICENSE
204              
205             This library is free software; you can redistribute it and/or modify
206             it under the same terms as Perl itself.
207              
208             =cut
209              
210             1;
211              
212             # vim: set ts=4 sw=4 tw=0 fdm=marker :
213