blib/lib/Algorithm/Classifier/IsolationForest/App/Command/explain.pm

filter: Statementstmt 75.2% 79 / 105 Branchbran 53.5% 30 / 56 Conditioncond 44.4% 8 / 18 MC/DCmcdc 10.0% 1 / 10 Subroutinesub 83.3% 10 / 12 Podpod 100% 5 / 5 totaltotal 64.5% 133 / 206 CC 42 SCAR 38.0
CC
42
Cov
65%
execute
63.8
validate
37.0
abstract
2.0
CRAP 44.9
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/accel.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/gblob.pm »
1 package Algorithm::Classifier::IsolationForest::App::Command::explain;
2  
3 86 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 86 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 86 ▶use Algorithm::Classifier::IsolationForest ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 86 ▶use Algorithm::Classifier::IsolationForest::App -command;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 86 ▶use Algorithm::Classifier::IsolationForest::App::Command::pack ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 86 ▶use File::Slurp qw(read_file write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 86 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 4 ▶sub opt_spec {
Subroutine opt_spec: called CC=1 SCAR=0.0
Pod documented
12 return (
13 [
14 4 'm=s',
15 'Input model JSON file path/name.',
16 { 'default' => 'iforest_model.json', 'completion' => 'files' }
17 ],
18 [ 'i=s', 'Input CSV for processing.', { 'completion' => 'files' } ],
19 [ 'o=s', 'Output to this file instead of printing.', { 'completion' => 'files' } ],
20 [ 'w', 'If the file specified via -o exists, over write it.', { 'completion' => 'files' } ],
21 [ 'method=s', "Attribution method, 'ablation' or 'path'.", { 'default' => 'ablation' } ],
22 [ 'n=i', 'Only output the top N features per row. 0 outputs every feature.', { 'default' => 0 } ],
23 [
24 't=f',
25 'Only explain rows whose anomaly score is >= this. 0 < $val < 1. Rows are scored first and only the flagged ones pay the explanation cost.'
26 ],
27 );
28 } ## end sub opt_spec
29  
30 0 ▶sub abstract { 'Explains which features drove each sample\'s anomaly score using the specified model' }
Subroutine abstract: not called CC=1 SCAR=6.9
Pod documented
31  
32 0 ▶sub description {
Subroutine description: not called CC=1 SCAR=6.9
Pod documented
33 0 'Explains which features drove each sample\'s anomaly score, via
34 explain_samples using the specified model.
35  
36 The input may be either a CSV (one row of features per line) or a
37 .iforest-packed binary produced by `iforest pack` (auto-detected via its
38 magic bytes).
39  
40 Output is one line per (row, feature) pair, features ordered most
41 responsible first. With the default ablation method:
42  
43 $row,$score,$rank,$feature,$weight,$value,$delta,$baseline
44  
45 and with --method path:
46  
47 $row,$score,$rank,$feature,$weight,$value
48  
49 $row is the 1-based input row number (so filtered output via -t still
50 references the input), $score the row\'s anomaly score, $rank 1 for the
51 most responsible feature counting up, $feature the feature name when the
52 model stores feature_names and the 0-based feature index otherwise,
53 $weight the feature\'s normalised share of the responsibility. Under
54 ablation, $delta is the score drop when $value is replaced by $baseline
55 (the per-feature typical value: the training-data median for batch
56 models, the window median for online models).
57  
58 Ablation scores n_features + 1 variants of every explained row, so on
59 large inputs pass -t to spend that only on the anomalous rows. See
60 "explain_samples" in perldoc Algorithm::Classifier::IsolationForest for
61 the methods\' trade-offs.
62 ';
63 } ## end sub description
64  
65 4 ▶sub validate {
Subroutine validate: called CC=14 SCAR=36.1
Pod documented
66 4 my ( $self, $opt, $args ) = @_;
67  
68 4 ▶ if ( !defined( $opt->{'i'} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opt->{'i'}) { } 0 4 4
elsif (not -f $opt->{'i'}) { } 0 4 4
elsif (not -r $opt->{'i'}) { } 0 4 4
69 0 $self->usage_error('-i has not been specified for a file to process');
70 } elsif ( !-f $opt->{'i'} ) {
71 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not a file or does not exist' );
72 } elsif ( !-r $opt->{'i'} ) {
73 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not readable' );
74 }
75  
76 4 ▶ if ( !-f $opt->{'m'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not -f $opt->{'m'}) { } 0 4 4
elsif (not -r $opt->{'m'}) { } 0 4 4
77 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not a file or does not exist' );
78 } elsif ( !-r $opt->{'m'} ) {
79 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not readable' );
80 }
81  
82 4 ▶ if ( defined( $opt->{'o'} ) && !$opt->{'w'} && -e $opt->{'o'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}) 0 4 4
Condition33%2/6
defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}
!ll&&!rl&&r
400
defined $opt->{"o"} and not $opt->{"w"}
!ll&&!rl&&r
400
MC/DC0%0/3
defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}
defined $opt->{"o"} not $opt->{"w"} -e $opt->{"o"}
Truth table25%1/4
A and not(B) and C
A= defined $opt->{"o"}B= not $opt->{"w"}C= -e $opt->{"o"}
ABCresult
0XX0
10X0
1100
1111
83 0 $self->usage_error( '-o, "' . $opt->{'o'} . '", already exists and -w is not specified' );
84 }
85  
86 4 ▶ if ( $opt->{'method'} !~ /\A(?:path|ablation)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opt->{"method"} =~ /\A(?:path|ablation)\z/) 1 3 4
87 1 $self->usage_error( '--method, "' . $opt->{'method'} . '", must be either \'path\' or \'ablation\'' );
88 }
89  
90 3 ▶ if ( $opt->{'n'} < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"n"} < 0) 0 3 3
91 0 $self->usage_error( '-n, "' . $opt->{'n'} . '", must be >= 0' );
92 }
93  
94 3 ▶ if ( defined( $opt->{'t'} ) && ( $opt->{'t'} <= 0 || $opt->{'t'} >= 1 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"t"} and $opt->{"t"} <= 0 || $opt->{"t"} >= 1) 0 3 3
Condition50%3/6
defined $opt->{"t"} and $opt->{"t"} <= 0 || $opt->{"t"} >= 1
!ll&&!rl&&r
210
$opt->{"t"} <= 0 or $opt->{"t"} >= 1
l!l&&r!l&&!r
001
MC/DC0%0/3
defined $opt->{"t"} and $opt->{"t"} <= 0 || $opt->{"t"} >= 1
defined $opt->{"t"} $opt->{"t"} <= 0 $opt->{"t"} >= 1
Truth table50%2/4
A and B or C
A= defined $opt->{"t"}B= $opt->{"t"} <= 0C= $opt->{"t"} >= 1
ABCresult
0XX0
1000
11X1
1011
95 0 $self->usage_error( '-t, "' . $opt->{'t'} . '", needs to be greater than 0 and less than 1' );
96 }
97  
98 3 return 1;
99 } ## end sub validate
100  
101 3 ▶sub execute {
Subroutine execute: called CC=29 SCAR=41.6
Pod documented
102 3 my ( $self, $opt, $args ) = @_;
103  
104 3 my $iforest = Algorithm::Classifier::IsolationForest->load( $opt->{'m'} );
105  
106 # A model carrying Algorithm::ToNumberMunger specs takes raw values in
107 # its munged CSV columns: skip the per-field numeric check at read
108 # time and munge the rows before explaining (re-checking numerics
109 # after), exactly as `iforest predict` does.
110 0 ▶ my $has_mungers = ref $iforest->{mungers} eq 'HASH' && %{ $iforest->{mungers} } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $iforest->{'mungers'} eq 'HASH' && %{$iforest->{'mungers'};} ? : 0 3 3
Condition33%1/3
ref $iforest->{"mungers"} eq "HASH" and %{$iforest->{"mungers"};}
!ll&&!rl&&r
300
MC/DC0%0/2
ref $iforest->{"mungers"} eq "HASH" and %{$iforest->{"mungers"};}
ref $iforest->{"mungers"} eq "HASH" %{$iforest->{"mungers"};}
Truth table33%1/3
A and B
A= ref $iforest->{"mungers"} eq "HASH"B= %{$iforest->{"mungers"};}
ABresult
0X0
100
111
111  
112 3 my $rows; # the numeric rows handed to score_samples/explain_samples
113  
114 3 ▶ if ( Algorithm::Classifier::IsolationForest::App::Command::pack::is_packed_file( $opt->{'i'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (Algorithm::Classifier::IsolationForest::App::Command::pack::is_packed_file($opt->{'i'})) { } 0 3 3
115 my ( $n_pts, $n_feats, $bytes )
116 0 = Algorithm::Classifier::IsolationForest::App::Command::pack::read_packed_file( $opt->{'i'} );
117 die "packed input has $n_feats features but model expects " . $iforest->{n_features} . "\n"
118 0 ▶ if $n_feats != $iforest->{n_features};
Branch: 1 branch
BranchTrueFalseTotal
if $n_feats != $iforest->{"n_features"} 0 0 0
119  
120 # Unlike predict, always unpack to per-row arrayrefs: explanations
121 # are per-feature (their values go in the output), online models
122 # take plain rows, and ablation rebuilds substituted variants from
123 # the rows anyway -- a packed fast path would buy nothing here.
124 0 my @doubles = unpack( 'd*', $bytes );
125 0 my @data;
126 0 for my $i ( 0 .. $n_pts - 1 ) {
127 0 push @data, [ @doubles[ $i * $n_feats .. ( $i + 1 ) * $n_feats - 1 ] ];
128 }
129 0 $rows = \@data;
130 } else {
131 # CSV path
132 3 my @data;
133 my $expected_cols;
134 3 my $line_int = 1;
135 3 foreach my $line ( read_file( $opt->{'i'} ) ) {
136 21 chomp($line);
137 21 ▶ next if $line =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*$/ 0 21 21
138  
139 21 my @fields = split( /,/, $line, -1 );
140  
141 21 ▶ if ( !defined($expected_cols) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $expected_cols) { } 3 18 21
elsif (scalar @fields != $expected_cols) { } 0 18 18
142 3 $expected_cols = scalar @fields;
143 3 ▶ die( 'Line ' . $line_int . ' of "' . $opt->{'i'} . '" has no columns' )
Branch: 1 branch
BranchTrueFalseTotal
if $expected_cols < 1 0 3 3
144 if $expected_cols < 1;
145 } elsif ( scalar @fields != $expected_cols ) {
146 die( 'Line '
147 . $line_int . ' of "'
148 0 . $opt->{'i'}
149 . '" has '
150 . scalar(@fields)
151 . ' columns but expected '
152 . $expected_cols );
153 }
154  
155 21 ▶ if ( !$has_mungers ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_mungers) 21 0 21
156 21 my $col_int = 1;
157 21 for my $field (@fields) {
158 die( 'Line '
159 . $line_int . ' of "'
160 63 ▶ . $opt->{'i'}
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($field) 0 63 63
161 . '" value for column '
162 . $col_int . ',"'
163 . $field
164 . '", does not appear to be a number' )
165 unless looks_like_number($field);
166 63 $col_int++;
167 } ## end for my $field (@fields)
168 } ## end if ( !$has_mungers )
169  
170 21 push @data, \@fields;
171  
172 21 $line_int++;
173 } ## end foreach my $line ( read_file( $opt->{'i'} ) )
174  
175 3 ▶ if ($has_mungers) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_mungers) { } 0 3 3
176 0 my $munged = $iforest->munge_rows( \@data );
177 0 for my $i ( 0 .. $#$munged ) {
178 0 for my $col ( 0 .. $#{ $munged->[$i] } ) {
179 die( 'Line '
180 . ( $i + 1 ) . ' of "'
181 0 ▶ . $opt->{'i'}
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($munged->[$i][$col]) 0 0 0
defined $munged->[$i][$col] ? : 0 0 0
182 . '" value for column '
183 . ( $col + 1 ) . ',"'
184 . ( defined $munged->[$i][$col] ? $munged->[$i][$col] : 'undef' )
185 . '", is not a number after munging' )
186 unless looks_like_number( $munged->[$i][$col] );
187 } ## end for my $col ( 0 .. $#{ $munged->[$i] } )
188 } ## end for my $i ( 0 .. $#$munged )
189 0 $rows = $munged;
190 } else {
191 3 $rows = \@data;
192 }
193 } ## end else [ if ( Algorithm::Classifier::IsolationForest::App::Command::pack::is_packed_file...)]
194  
195 # With -t, score everything first (cheap) and only explain the rows
196 # that clear the cutoff -- under ablation each explained row costs
197 # n_features + 1 scored variants, so this is the difference between
198 # explaining a handful of anomalies and re-scoring the file N times.
199 3 my @explain_idx;
200 3 ▶ if ( defined $opt->{'t'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{'t'}) { } 1 2 3
201 1 my $scores = $iforest->score_samples($rows);
202 1 @explain_idx = grep { $scores->[$_] >= $opt->{'t'} } 0 .. $#$scores;
203 } else {
204 2 @explain_idx = 0 .. $#$rows;
205 }
206  
207 3 my $results_string = '';
208 3 ▶ if (@explain_idx) {
Branch: 1 branch
BranchTrueFalseTotal
if (@explain_idx) 3 0 3
209 3 my $subset = [ @{$rows}[@explain_idx] ];
210 3 my $explanations = $iforest->explain_samples( $subset, method => $opt->{'method'} );
211  
212 3 for my $k ( 0 .. $#explain_idx ) {
213 16 my $row_num = $explain_idx[$k] + 1;
214 16 my $e = $explanations->[$k];
215 16 my $features = $e->{features};
216 my $limit
217 = ( $opt->{'n'} && $opt->{'n'} < scalar @$features )
218 16 ▶ ? $opt->{'n'}
Branch: 1 branch
BranchTrueFalseTotal
$opt->{'n'} && $opt->{'n'} < scalar @$features ? : 9 7 16
Condition66%2/3
$opt->{"n"} and $opt->{"n"} < scalar @$features
!ll&&!rl&&r
709
MC/DC50%1/2
$opt->{"n"} and $opt->{"n"} < scalar @$features
$opt->{"n"} $opt->{"n"} < scalar @$features
Truth table66%2/3
A and B
A= $opt->{"n"}B= $opt->{"n"} < scalar @$features
ABresult
0X0
100
111
219 : scalar @$features;
220 16 for my $rank ( 1 .. $limit ) {
221 30 my $f = $features->[ $rank - 1 ];
222 my @cols = (
223 $row_num, $e->{score}, $rank, ( defined $f->{name} ? $f->{name} : $f->{index} ),
224 30 ▶ $f->{weight}, ( defined $f->{value} ? $f->{value} : '' ),
Branch: 2 branches
BranchTrueFalseTotal
defined $f->{'name'} ? : 0 30 30
defined $f->{'value'} ? : 30 0 30
225 );
226 30 ▶ push @cols, $f->{delta}, $f->{baseline} if $e->{method} eq 'ablation';
Branch: 1 branch
BranchTrueFalseTotal
if $e->{"method"} eq "ablation" 23 7 30
227 30 $results_string .= join( ',', @cols ) . "\n";
228 }
229 } ## end for my $k ( 0 .. $#explain_idx )
230 } ## end if (@explain_idx)
231  
232 3 ▶ if ( !defined( $opt->{'o'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opt->{"o"}) 3 0 3
233 3 print $results_string;
234 3 exit 0;
235 }
236  
237 0 write_file( $opt->{'o'}, { 'atomic' => 1 }, $results_string );
238 } ## end sub execute
239  
240 =head1 NAME
241  
242 Algorithm::Classifier::IsolationForest::App::Command::explain - Explains which features drove each sample's anomaly score using the specified model
243  
244 =head1 DESCRIPTION
245  
246 Runs C<explain_samples> over the input and prints one line per (row,
247 feature) pair, most responsible feature first. Input may be a CSV or a
248 C<.iforest-packed> binary from C<iforest pack>, detected by its magic
249 bytes.
250  
251 Under the default ablation method the line format is
252  
253 $row,$score,$rank,$feature,$weight,$value,$delta,$baseline
254  
255 and under C<--method path>
256  
257 $row,$score,$rank,$feature,$weight,$value
258  
259 C<$row> is the 1-based input row number, so output filtered by C<-t>
260 still points back at the input. Ablation scores C<n_features + 1>
261 variants of every explained row, which is why C<-t> is worth reaching for
262 on a large input: it spends that only on the rows that cleared the cutoff.
263  
264 Run it as C<iforest explain>; C<iforest help explain> lists every option.
265  
266 =head1 METHODS
267  
268 L<App::Cmd> calls these while dispatching the subcommand. Nothing else
269 should.
270  
271 =head2 opt_spec
272  
273 Returns this command's option specifications, as the list of arrayrefs
274 L<Getopt::Long::Descriptive> expects.
275  
276 =head2 abstract
277  
278 Returns the one-line summary C<iforest commands> prints beside the
279 command name.
280  
281 =head2 description
282  
283 Returns the long help text C<iforest help explain> prints under the option
284 list.
285  
286 =head2 validate
287  
288 Checks the parsed options before anything is read or written, so a
289 mistake costs nothing.
290  
291 Checks that C<-i> and C<-m> name readable files, that C<-o> may be
292 written, that C<--method> is C<ablation> or C<path>, that C<-n> is not
293 negative, and that C<-t> lies in (0, 1).
294  
295 Takes the parsed options hashref and the arrayref of remaining
296 arguments. Calls C<usage_error>, which prints the usage and exits, on
297 the first problem it finds, and returns 1 when everything checks out.
298  
299 =head2 execute
300  
301 Loads the model, reads the input, optionally filters by C<-t>, and prints
302 the per-feature lines to STDOUT or to C<-o>.
303  
304 Takes the parsed options hashref and the arrayref of remaining
305 arguments, and returns 1.
306  
307 =cut
308  
309 86 return 1;
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/accel.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/gblob.pm »