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

filter: Statementstmt 86.1% 124 / 144 Branchbran 67.2% 82 / 122 Conditioncond 57.1% 24 / 42 MC/DCmcdc 24.0% 6 / 25 Subroutinesub 83.3% 10 / 12 Podpod 100% 5 / 5 totaltotal 71.7% 251 / 350 CC 81 SCAR 43.0
CC
81
Cov
75%
validate
100.3
execute
74.4
abstract
2.0
CRAP 73.5
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/csv2plot.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/streamd.pm »
1 package Algorithm::Classifier::IsolationForest::App::Command::stream;
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::Online ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 86 ▶use Algorithm::Classifier::IsolationForest::App -command;
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 10 ▶sub opt_spec {
Subroutine opt_spec: called CC=1 SCAR=0.0
Pod documented
12 return (
13 [
14 10 'm=s',
15 'Online model JSON file path/name. Created if it does not exist; resumed and updated if it does.',
16 { 'default' => 'oiforest_model.json', 'completion' => 'files' }
17 ],
18 [ 'i=s', 'Input CSV to stream through the model, in row order.', { 'completion' => 'files' } ],
19 [ 'o=s', 'Output the scores to this file instead of printing.', { 'completion' => 'files' } ],
20 [ 'w', 'If the file specified via -o exists, over write it.' ],
21 [ 'd', 'Include the input data in the output.' ],
22 [
23 'learn-only',
24 'Only learn the input (warm-up); no scores are emitted. May not be combined with --score-only.'
25 ],
26 [
27 'score-only',
28 'Only score the input against the model as-is; nothing is learned. May not be combined with --learn-only.'
29 ],
30 [ 'threshold=f', 'Alternative decision threshold to use for the label column. 0 < $val < 1' ],
31 [
32 'save!',
33 'Save the updated model state back to -m after streaming (default on; --no-save to discard).',
34 { 'default' => 1 }
35 ],
36  
37 # creation knobs, used only when -m does not exist yet
38 [ 'n=i', 'Number of isolation trees in the ensemble (new models only).' ],
39 [ 'window=i', 'Sliding window size; 0 disables forgetting (new models only).' ],
40 [ 'eta=i', 'max_leaf_samples: points a leaf accumulates before splitting (new models only).' ],
41 [ 'growth=s', "Leaf split-requirement growth, 'adaptive' or 'fixed' (new models only)." ],
42 [ 'subsample=f', 'Per-tree stream subsampling probability, in (0, 1] (new models only).' ],
43 [ 's=i', 'Seed int (new models only).' ],
44 [
45 'c=f',
46 'Contamination. Expected fraction of anomalies, in (0, 0.5]; learns the decision threshold from the window (new models only).'
47 ],
48 [
49 't=s@',
50 'Feature name tag. Pass once per feature (e.g. -t cpu -t mem -t disk); the count must match the number of CSV columns or the command will die (new models only).'
51 ],
52 [
53 'mungers=s',
54 'JSON file of Algorithm::ToNumberMunger specs, keyed by feature tag (new models only; requires -t). '
55 . 'Munged CSV columns may hold raw values; rows are munged before streaming and the spec is '
56 . 'saved with the model, so resumed runs munge identically. Scalar mungers only for CSV input.',
57 { 'completion' => 'files' }
58 ],
59 [
60 'prototype=s',
61 'JSON prototype file to create the model from (new models only): the variable schema and '
62 . 'schema_version/schema_description come from it, and its params supply knob defaults that the '
63 . 'creation switches override. May not be combined with -t or --mungers. See PROTOTYPES in the '
64 . 'module POD.',
65 { 'completion' => 'files' }
66 ],
67 );
68 } ## end sub opt_spec
69  
70 0 ▶sub abstract { 'Stream CSV rows through an Online Isolation Forest model, scoring and learning as it goes' }
Subroutine abstract: not called CC=1 SCAR=6.9
Pod documented
71  
72 0 ▶sub description {
Subroutine description: not called CC=1 SCAR=6.9
Pod documented
73 0 'Streams the input rows, in order, through an Online Isolation Forest
74 model (Algorithm::Classifier::IsolationForest::Online).
75  
76 The default operation is prequential: each row is scored against the
77 model as it stood before that row was learned, then learned, and the
78 model state (including its sliding window) is saved back to -m so the
79 next invocation resumes the stream where this one left off. --learn-only
80 skips the scoring (warm-up) and --score-only skips the learning.
81  
82 If -m does not exist yet a new model is created using the creation knobs
83 (-n, --window, --eta, --growth, --subsample, -s, -c, -t, --mungers,
84 --prototype); when it does exist those knobs are ignored. With
85 --prototype the schema and schema_version/schema_description come from
86 the prototype file, its params supply knob defaults, and the other
87 creation switches override those params.
88  
89 The input format matches `iforest fit`: CSV, all columns numeric
90 features, one sample per row.
91  
92 Output format is one line per input row.
93  
94 $score,$label
95  
96 If -d is specified all input feature columns are prepended.
97  
98 $feat1,...,$featN,$score,$label
99  
100 Switches to new args for new models are like below...
101  
102 -n -> n_trees
103 --window -> window_size
104 --eta -> max_leaf_samples
105 --growth -> growth
106 --subsample -> subsample
107 -s -> seed
108 -c -> contamination
109 -t -> feature_names
110 ';
111 } ## end sub description
112  
113 10 ▶sub validate {
Subroutine validate: called CC=25 SCAR=46.1
Pod documented
114 10 my ( $self, $opt, $args ) = @_;
115  
116 10 ▶ if ( !defined( $opt->{'i'} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opt->{'i'}) { } 0 10 10
elsif (not -f $opt->{'i'}) { } 0 10 10
elsif (not -r $opt->{'i'}) { } 0 10 10
117 0 $self->usage_error('-i has not been specified for a file to process');
118 } elsif ( !-f $opt->{'i'} ) {
119 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not a file or does not exist' );
120 } elsif ( !-r $opt->{'i'} ) {
121 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not readable' );
122 }
123  
124 10 ▶ if ( -e $opt->{'m'} && !-r $opt->{'m'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $opt->{"m"} and not -r $opt->{"m"}) 0 10 10
Condition66%2/3
-e $opt->{"m"} and not -r $opt->{"m"}
!ll&&!rl&&r
460
MC/DC0%0/2
-e $opt->{"m"} and not -r $opt->{"m"}
-e $opt->{"m"} not -r $opt->{"m"}
Truth table66%2/3
A and not(B)
A= -e $opt->{"m"}B= not -r $opt->{"m"}
ABresult
0X0
100
111
125 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", exists but is not readable' );
126 }
127  
128 10 ▶ if ( $opt->{'learn_only'} && $opt->{'score_only'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"learn_only"} and $opt->{"score_only"}) 0 10 10
Condition66%2/3
$opt->{"learn_only"} and $opt->{"score_only"}
!ll&&!rl&&r
910
MC/DC0%0/2
$opt->{"learn_only"} and $opt->{"score_only"}
$opt->{"learn_only"} $opt->{"score_only"}
Truth table66%2/3
A and B
A= $opt->{"learn_only"}B= $opt->{"score_only"}
ABresult
0X0
100
111
129 0 $self->usage_error('--learn-only and --score-only may not be combined');
130 }
131  
132 10 ▶ 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 10 10
Condition66%4/6
defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}
!ll&&!rl&&r
910
defined $opt->{"o"} and not $opt->{"w"}
!ll&&!rl&&r
901
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 table50%2/4
A and not(B) and C
A= defined $opt->{"o"}B= not $opt->{"w"}C= -e $opt->{"o"}
ABCresult
0XX0
10X0
1100
1111
133 0 $self->usage_error( '-o, "' . $opt->{'o'} . '", already exists and -w is not specified' );
134 }
135  
136 10 ▶ if ( defined( $opt->{'threshold'} ) && ( $opt->{'threshold'} <= 0 || $opt->{'threshold'} >= 1 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"threshold"} and $opt->{"threshold"} <= 0 || $opt->{"threshold"} >= 1) 0 10 10
Condition16%1/6
defined $opt->{"threshold"} and $opt->{"threshold"} <= 0 || $opt->{"threshold"} >= 1
!ll&&!rl&&r
1000
$opt->{"threshold"} <= 0 or $opt->{"threshold"} >= 1
l!l&&r!l&&!r
000
MC/DC0%0/3
defined $opt->{"threshold"} and $opt->{"threshold"} <= 0 || $opt->{"threshold"} >= 1
defined $opt->{"threshold"} $opt->{"threshold"} <= 0 $opt->{"threshold"} >= 1
Truth table25%1/4
A and B or C
A= defined $opt->{"threshold"}B= $opt->{"threshold"} <= 0C= $opt->{"threshold"} >= 1
ABCresult
0XX0
1000
11X1
1011
137 0 $self->usage_error( '--threshold, "' . $opt->{'threshold'} . '", needs to be greater than 0 and less than 1' );
138 }
139  
140 10 ▶ if ( defined( $opt->{'growth'} ) && $opt->{'growth'} !~ /\A(?:adaptive|fixed)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"growth"} and not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/) 0 10 10
Condition33%1/3
defined $opt->{"growth"} and not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/
!ll&&!rl&&r
1000
MC/DC0%0/2
defined $opt->{"growth"} and not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/
defined $opt->{"growth"} not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/
Truth table33%1/3
A and not(B)
A= defined $opt->{"growth"}B= not $opt->{"growth"} =~ /\A(?:adaptive|fixed)\z/
ABresult
0X0
100
111
141 0 $self->usage_error( '--growth, "' . $opt->{'growth'} . '", must be either adaptive or fixed' );
142 }
143  
144 10 ▶ if ( defined( $opt->{'mungers'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"mungers"}) 1 9 10
145 1 ▶ if ( !-f $opt->{'mungers'} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not -f $opt->{'mungers'}) { } 0 1 1
elsif (not -r $opt->{'mungers'}) { } 0 1 1
elsif (not defined $opt->{'t'}) { } 0 1 1
146 0 $self->usage_error( '--mungers, "' . $opt->{'mungers'} . '", is not a file or does not exist' );
147 } elsif ( !-r $opt->{'mungers'} ) {
148 0 $self->usage_error( '--mungers, "' . $opt->{'mungers'} . '", is not readable' );
149 } elsif ( !defined( $opt->{'t'} ) ) {
150 0 $self->usage_error('--mungers requires feature tags (-t) to compile against');
151 }
152 }
153  
154 10 ▶ if ( defined( $opt->{'prototype'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"prototype"}) 3 7 10
155 3 ▶ if ( !-f $opt->{'prototype'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not -f $opt->{'prototype'}) { } 0 3 3
elsif (not -r $opt->{'prototype'}) { } 0 3 3
156 0 $self->usage_error( '--prototype, "' . $opt->{'prototype'} . '", is not a file or does not exist' );
157 } elsif ( !-r $opt->{'prototype'} ) {
158 0 $self->usage_error( '--prototype, "' . $opt->{'prototype'} . '", is not readable' );
159 }
160 3 ▶ if ( defined( $opt->{'t'} ) || defined( $opt->{'mungers'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"t"} or defined $opt->{"mungers"}) 0 3 3
Condition33%1/3
defined $opt->{"t"} or defined $opt->{"mungers"}
l!l&&r!l&&!r
003
MC/DC0%0/2
defined $opt->{"t"} or defined $opt->{"mungers"}
defined $opt->{"t"} defined $opt->{"mungers"}
Truth table33%1/3
A or B
A= defined $opt->{"t"}B= defined $opt->{"mungers"}
ABresult
1X1
011
000
161 0 $self->usage_error(
162 '--prototype may not be combined with -t or --mungers; the schema comes only from the prototype');
163 }
164 } ## end if ( defined( $opt->{'prototype'} ) )
165  
166 10 return 1;
167 } ## end sub validate
168  
169 10 ▶sub execute {
Subroutine execute: called CC=57 SCAR=43.1
Pod documented
170 10 my ( $self, $opt, $args ) = @_;
171  
172 # --- resume an existing model first ------------------------------------
173 # Loaded before the CSV is read because a munger-bearing model changes
174 # how the CSV is validated (munged columns hold raw values).
175 10 my $oif;
176 10 ▶ if ( -f $opt->{'m'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $opt->{"m"}) 6 4 10
177 6 $oif = Algorithm::Classifier::IsolationForest->load( $opt->{'m'} );
178 6 ▶ die( '-m, "' . $opt->{'m'} . '", is not an online model; stream only works on those' . "\n" )
Branch: 1 branch
BranchTrueFalseTotal
unless ref $oif eq "Algorithm::Classifier::IsolationForest::Online" 1 5 6
179 unless ref $oif eq 'Algorithm::Classifier::IsolationForest::Online';
180 }
181  
182 # Prototype creation, new models only like the other creation knobs.
183 # Done before the CSV is read for the same reason resuming is: a
184 # munger-bearing prototype changes how the CSV is validated. The
185 # explicit creation switches override the prototype's params.
186 9 my $from_proto = 0;
187 9 ▶ if ( !$oif && defined( $opt->{'prototype'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $oif and defined $opt->{"prototype"}) 2 7 9
Condition100%3/3
not $oif and defined $opt->{"prototype"}
!ll&&!rl&&r
522
MC/DC100%2/2
not $oif and defined $opt->{"prototype"}
not $oif defined $opt->{"prototype"}
Truth table100%3/3
not(A) and B
A= not $oifB= defined $opt->{"prototype"}
ABresult
0X0
100
111
188 2 my $proto = eval {
189 2 Algorithm::Classifier::IsolationForest->validate_prototype( scalar read_file( $opt->{'prototype'} ) );
190 };
191 2 ▶ die( '--prototype, "' . $opt->{'prototype'} . '", is not a valid prototype: ' . $@ ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 2 2
192 die( '--prototype, "' . $opt->{'prototype'} . '", is for a batch model; use `iforest fit`' . "\n" )
193 2 ▶ unless $proto->{class} eq 'online';
Branch: 1 branch
BranchTrueFalseTotal
unless $proto->{"class"} eq "online" 1 1 2
194  
195 1 my %overrides;
196 1 ▶ $overrides{'n_trees'} = $opt->{'n'} if defined $opt->{'n'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"n"} 0 1 1
197 1 ▶ $overrides{'window_size'} = $opt->{'window'} if defined $opt->{'window'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"window"} 0 1 1
198 1 ▶ $overrides{'max_leaf_samples'} = $opt->{'eta'} if defined $opt->{'eta'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"eta"} 0 1 1
199 1 ▶ $overrides{'growth'} = $opt->{'growth'} if defined $opt->{'growth'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"growth"} 0 1 1
200 1 ▶ $overrides{'subsample'} = $opt->{'subsample'} if defined $opt->{'subsample'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"subsample"} 0 1 1
201 1 ▶ $overrides{'seed'} = $opt->{'s'} if defined $opt->{'s'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"s"} 1 0 1
202 1 ▶ $overrides{'contamination'} = $opt->{'c'} if defined $opt->{'c'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"c"} 0 1 1
203  
204 1 $oif = eval { Algorithm::Classifier::IsolationForest->new_from_prototype( $proto, %overrides ) };
205 1 ▶ die( '--prototype, "' . $opt->{'prototype'} . '", failed to create a model: ' . $@ ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
206 1 $from_proto = 1;
207 } ## end if ( !$oif && defined( $opt->{'prototype'}...))
208  
209 # Munger spec for a NEW model (an existing model carries its own; the
210 # creation knob is ignored then, like the rest of them).
211 8 my $mungers;
212 8 ▶ if ( !$oif && defined( $opt->{'mungers'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $oif and defined $opt->{"mungers"}) 1 7 8
Condition100%3/3
not $oif and defined $opt->{"mungers"}
!ll&&!rl&&r
611
MC/DC100%2/2
not $oif and defined $opt->{"mungers"}
not $oif defined $opt->{"mungers"}
Truth table100%3/3
not(A) and B
A= not $oifB= defined $opt->{"mungers"}
ABresult
0X0
100
111
213 1 require JSON::PP;
214 1 $mungers = eval { JSON::PP->new->decode( scalar read_file( $opt->{'mungers'} ) ) };
215 1 ▶ die( '--mungers, "' . $opt->{'mungers'} . '", did not parse as JSON: ' . $@ ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
216 1 ▶ die( '--mungers, "' . $opt->{'mungers'} . '", must be a JSON object of tag => spec' )
Branch: 1 branch
BranchTrueFalseTotal
unless ref $mungers eq "HASH" 0 1 1
217 unless ref $mungers eq 'HASH';
218 }
219  
220 my $has_mungers
221 = $oif
222 8 ▶ ? ( ref $oif->{mungers} eq 'HASH' && %{ $oif->{mungers} } ? 1 : 0 )
Branch: 3 branches
BranchTrueFalseTotal
$oif ? : 6 2 8
ref $oif->{'mungers'} eq 'HASH' && %{$oif->{'mungers'};} ? : 1 5 6
$mungers ? : 1 1 2
Condition66%2/3
ref $oif->{"mungers"} eq "HASH" and %{$oif->{"mungers"};}
!ll&&!rl&&r
501
MC/DC50%1/2
ref $oif->{"mungers"} eq "HASH" and %{$oif->{"mungers"};}
ref $oif->{"mungers"} eq "HASH" %{$oif->{"mungers"};}
Truth table66%2/3
A and B
A= ref $oif->{"mungers"} eq "HASH"B= %{$oif->{"mungers"};}
ABresult
0X0
100
111
223 : ( $mungers ? 1 : 0 );
224  
225 # --- read the CSV, exactly like `iforest fit` does -------------------
226 8 my @data;
227 my $expected_cols;
228  
229 8 my $line_int = 1;
230 8 foreach my $line ( read_file( $opt->{'i'} ) ) {
231 752 chomp($line);
232 752 ▶ next if $line =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*$/ 0 752 752
233  
234 752 my @fields = split( /,/, $line, -1 );
235  
236 752 ▶ if ( !defined($expected_cols) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $expected_cols) { } 8 744 752
elsif (scalar @fields != $expected_cols) { } 0 744 744
237 8 $expected_cols = scalar @fields;
238 8 ▶ die( 'Line ' . $line_int . ' of "' . $opt->{'i'} . '" has no columns' )
Branch: 1 branch
BranchTrueFalseTotal
if $expected_cols < 1 0 8 8
239 if $expected_cols < 1;
240 } elsif ( scalar @fields != $expected_cols ) {
241 die( 'Line '
242 . $line_int . ' of "'
243 0 . $opt->{'i'}
244 . '" has '
245 . scalar(@fields)
246 . ' columns but expected '
247 . $expected_cols );
248 }
249  
250 752 ▶ if ( !$has_mungers ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_mungers) 590 162 752
251 590 my $col_int = 1;
252 590 for my $field (@fields) {
253 die( 'Line '
254 . $line_int . ' of "'
255 1770 ▶ . $opt->{'i'}
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($field) 0 1770 1770
256 . '" value for column '
257 . $col_int . ',"'
258 . $field
259 . '", does not appear to be a number' )
260 unless looks_like_number($field);
261 1770 $col_int++;
262 } ## end for my $field (@fields)
263 } ## end if ( !$has_mungers )
264  
265 752 push @data, \@fields;
266  
267 752 $line_int++;
268 } ## end foreach my $line ( read_file( $opt->{'i'} ) )
269  
270 # A prototype-created model already carries its tags; hold them to the
271 # same CSV-width check the -t path gets.
272 8 ▶ if ($from_proto) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from_proto) 1 7 8
273 1 my $n_tags = scalar @{ $oif->feature_names };
274 1 ▶ my $n_features = defined($expected_cols) ? $expected_cols : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $expected_cols ? : 1 0 1
275 1 ▶ die( 'Number of prototype feature_names ('
Branch: 1 branch
BranchTrueFalseTotal
unless $n_tags == $n_features 0 1 1
276 . $n_tags
277 . ') does not match number of CSV columns ('
278 . $n_features
279 . ')' )
280 unless $n_tags == $n_features;
281 } ## end if ($from_proto)
282  
283 # --- create the model when not resuming --------------------------------
284 8 ▶ if ( !$oif ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($oif) 2 6 8
285 2 ▶ if ( defined( $opt->{'t'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"t"}) 1 1 2
286 1 my $n_tags = scalar @{ $opt->{'t'} };
287 1 ▶ my $n_features = defined($expected_cols) ? $expected_cols : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $expected_cols ? : 1 0 1
288 1 ▶ die( 'Number of feature tags (' . $n_tags . ') does not match number of CSV columns (' . $n_features . ')' )
Branch: 1 branch
BranchTrueFalseTotal
unless $n_tags == $n_features 0 1 1
289 unless $n_tags == $n_features;
290 }
291 $oif = Algorithm::Classifier::IsolationForest::Online->new(
292 'n_trees' => $opt->{'n'},
293 'window_size' => $opt->{'window'},
294 'max_leaf_samples' => $opt->{'eta'},
295 'growth' => $opt->{'growth'},
296 'subsample' => $opt->{'subsample'},
297 'seed' => $opt->{'s'},
298 'contamination' => $opt->{'c'},
299 2 'feature_names' => $opt->{'t'},
300 'mungers' => $mungers,
301 );
302 } ## end if ( !$oif )
303  
304 # Munge the raw rows into numbers, then run the numeric validation
305 # that was skipped at read time. Munged into a separate structure so
306 # -d still prints the raw input columns as given.
307 8 my $stream_rows = \@data;
308 8 ▶ if ($has_mungers) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_mungers) 2 6 8
309 2 my $munged = $oif->munge_rows( \@data );
310 2 for my $i ( 0 .. $#$munged ) {
311 162 for my $col ( 0 .. $#{ $munged->[$i] } ) {
312 die( 'Line '
313 . ( $i + 1 ) . ' of "'
314 486 ▶ . $opt->{'i'}
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($munged->[$i][$col]) 0 486 486
defined $munged->[$i][$col] ? : 0 0 0
315 . '" value for column '
316 . ( $col + 1 ) . ',"'
317 . ( defined $munged->[$i][$col] ? $munged->[$i][$col] : 'undef' )
318 . '", is not a number after munging' )
319 unless looks_like_number( $munged->[$i][$col] );
320 } ## end for my $col ( 0 .. $#{ $munged->[$i] } )
321 } ## end for my $i ( 0 .. $#$munged )
322 2 $stream_rows = $munged;
323 } ## end if ($has_mungers)
324  
325 # --- stream ------------------------------------------------------------
326 8 my $results_string = '';
327 8 ▶ if ( $opt->{'learn_only'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{'learn_only'}) { } 1 7 8
328 1 $oif->learn($stream_rows);
329 } else {
330 7 my $scores;
331 7 ▶ if ( $opt->{'score_only'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{'score_only'}) { } 1 6 7
332 1 $scores = $oif->score_samples($stream_rows);
333 } else {
334 6 $scores = $oif->score_learn($stream_rows);
335 }
336  
337 my $threshold
338 7 ▶ = defined $opt->{'threshold'} ? $opt->{'threshold'}
Branch: 2 branches
BranchTrueFalseTotal
defined $opt->{'threshold'} ? : 0 7 7
defined $oif->decision_threshold ? : 0 7 7
339 : defined $oif->decision_threshold ? $oif->decision_threshold
340 : 0.5;
341  
342 7 for my $i ( 0 .. $#$scores ) {
343 631 ▶ my $label = $scores->[$i] >= $threshold ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$scores->[$i] >= $threshold ? : 51 580 631
344 631 ▶ if ( $opt->{'d'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{'d'}) { } 0 631 631
345 0 $results_string .= join( ',', @{ $data[$i] } ) . ',' . $scores->[$i] . ',' . $label . "\n";
346 } else {
347 631 $results_string .= $scores->[$i] . ',' . $label . "\n";
348 }
349 }
350 } ## end else [ if ( $opt->{'learn_only'} ) ]
351  
352 # Refresh the contamination threshold against the post-stream window so
353 # the saved model's default cutoff tracks the stream.
354 8 ▶ if ( !$opt->{'score_only'} && defined $oif->{contamination} && $oif->window_count ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $opt->{"score_only"} and defined $oif->{"contamination"} and $oif->window_count) 0 8 8
Condition50%3/6
not $opt->{"score_only"} and defined $oif->{"contamination"} and $oif->window_count
!ll&&!rl&&r
800
not $opt->{"score_only"} and defined $oif->{"contamination"}
!ll&&!rl&&r
170
MC/DC0%0/3
not $opt->{"score_only"} and defined $oif->{"contamination"} and $oif->window_count
not $opt->{"score_only"} defined $oif->{"contamination"} $oif->window_count
Truth table50%2/4
not(A) and B and C
A= not $opt->{"score_only"}B= defined $oif->{"contamination"}C= $oif->window_count
ABCresult
0XX0
10X0
1100
1111
355 0 $oif->relearn_threshold;
356 }
357  
358 8 ▶ if ( $opt->{'save'} && !$opt->{'score_only'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"save"} and not $opt->{"score_only"}) 7 1 8
Condition66%2/3
$opt->{"save"} and not $opt->{"score_only"}
!ll&&!rl&&r
017
MC/DC50%1/2
$opt->{"save"} and not $opt->{"score_only"}
$opt->{"save"} not $opt->{"score_only"}
Truth table66%2/3
A and not(B)
A= $opt->{"save"}B= not $opt->{"score_only"}
ABresult
0X0
100
111
359 7 $oif->save( $opt->{'m'} );
360 }
361  
362 8 ▶ if ( length $results_string ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $results_string) 7 1 8
363 7 ▶ if ( !defined( $opt->{'o'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $opt->{'o'}) { } 6 1 7
364 6 print $results_string;
365 } else {
366 1 write_file( $opt->{'o'}, { 'atomic' => 1 }, $results_string );
367 }
368 }
369  
370 8 return 1;
371 } ## end sub execute
372  
373 =head1 NAME
374  
375 Algorithm::Classifier::IsolationForest::App::Command::stream - Stream CSV rows through an Online Isolation Forest model, scoring and learning as it goes
376  
377 =head1 DESCRIPTION
378  
379 Streams the input rows, in order, through an
380 L<Algorithm::Classifier::IsolationForest::Online> model.
381  
382 The default is prequential: each row is scored against the model as it
383 stood before that row was learned, then learned, and the model state --
384 sliding window included -- is saved back to C<-m>, so the next invocation
385 resumes the stream where this one left off. C<--learn-only> skips the
386 scoring, which is what a warm-up wants; C<--score-only> skips the
387 learning.
388  
389 When C<-m> does not exist yet the creation knobs build a new model; when
390 it does exist they are ignored. With C<--prototype> the schema and its
391 version and description come from the prototype file, its params supply
392 the knob defaults, and the other creation switches override those params.
393  
394 Input matches C<iforest fit>: CSV, every column a numeric feature, one
395 sample per row. Output is one line per input row:
396  
397 $score,$label
398  
399 With C<-d> the input feature columns are prepended.
400  
401 Run it as C<iforest stream>; C<iforest help stream> lists every option.
402  
403 =head1 METHODS
404  
405 L<App::Cmd> calls these while dispatching the subcommand. Nothing else
406 should.
407  
408 =head2 opt_spec
409  
410 Returns this command's option specifications, as the list of arrayrefs
411 L<Getopt::Long::Descriptive> expects.
412  
413 =head2 abstract
414  
415 Returns the one-line summary C<iforest commands> prints beside the
416 command name.
417  
418 =head2 description
419  
420 Returns the long help text C<iforest help stream> prints under the option
421 list.
422  
423 =head2 validate
424  
425 Checks the parsed options before anything is read or written, so a
426 mistake costs nothing.
427  
428 Checks that C<-i> names a readable CSV, that C<-m> is usable, that
429 C<--learn-only> and C<--score-only> are not combined, that the numeric
430 knobs parse, and that a C<--mungers> spec is readable and accompanied by
431 the feature tags (C<-t>) it compiles against.
432  
433 Takes the parsed options hashref and the arrayref of remaining
434 arguments. Calls C<usage_error>, which prints the usage and exits, on
435 the first problem it finds, and returns 1 when everything checks out.
436  
437 =head2 execute
438  
439 Creates or resumes the model, runs the stream, prints the result lines,
440 and saves the updated model back to C<-m>.
441  
442 Takes the parsed options hashref and the arrayref of remaining
443 arguments, and returns 1.
444  
445 =cut
446  
447 86 return 1;
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/csv2plot.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/streamd.pm »