blib/lib/Algorithm/AM.pm

filter: Statementstmt 98.6% 146 / 148 Branchbran 94.1% 32 / 34 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 18 / 18 Podpod 66.6% 2 / 3 totaltotal 97.5% 198 / 203 CC 22 SCAR 18.8
CC
22
Cov
98%
classify
14.0
_context_label
5.0
BUILD
4.0
CRAP 6.5
« blib/lib/Algorithm/AM/Batch.pm ↑ Summary blib/lib/Algorithm/AM/Result.pm »
1 package Algorithm::AM;
2 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 10 our $VERSION = '3.13';
5 # ABSTRACT: Classify data with Analogical Modeling
6 10 ▶use feature 'state';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 10 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 10 our @CARP_NOT = qw(Algorithm::AM);
9  
10 # Place this accessor here so that Class::Tiny doesn't generate
11 # a getter/setter pair.
12 389 ▶sub training_set {
Subroutine training_set: called CC=1 SCAR=0.0
Pod documented
13 389 my ($self) = @_;
14 389 return $self->{training_set};
15 }
16  
17 10 ▶use Class::Tiny qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
18 exclude_nulls
19 exclude_given
20 linear
21 training_set
22 ), {
23 exclude_nulls => 1,
24 exclude_given => 1,
25 linear => 0,
26 10 };
27  
28 195 ▶sub BUILD {
Subroutine BUILD: called CC=4 SCAR=13.9
Pod undocumented
29 195 my ($self, $args) = @_;
30  
31 # check for invalid arguments
32 195 my $class = ref $self;
33 195 my %valid_attrs = map {$_ => 1}
34 Class::Tiny->get_all_attributes_for($class);
35 195 my @invalids = grep {!$valid_attrs{$_}} sort keys %$args;
36 195 ▶ if(@invalids){
Branch: 1 branch
BranchTrueFalseTotal
if (@invalids) 1 194 195
37 1 croak "Invalid attributes for $class: " . join ' ',
38 sort @invalids;
39 }
40  
41 194 ▶ if(!exists $args->{training_set}){
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $args->{"training_set"}) 1 193 194
42 1 croak "Missing required parameter 'training_set'";
43 }
44  
45 193 ▶ if('Algorithm::AM::DataSet' ne ref $args->{training_set}){
Branch: 1 branch
BranchTrueFalseTotal
if ("Algorithm::AM::DataSet" ne ref $args->{"training_set"}) 1 192 193
46 1 croak 'Parameter training_set should ' .
47 'be an Algorithm::AM::DataSet';
48 }
49 192 $self->_initialize();
50 # delete $args->{training_set};
51 192 return;
52 }
53  
54 10 ▶use Algorithm::AM::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
55 10 ▶use Algorithm::AM::BigInt 'bigcmp';
Subroutine BEGIN: called CC=1 SCAR=0.0
56 10 ▶use Algorithm::AM::DataSet;
Subroutine BEGIN: called CC=1 SCAR=0.0
57 10 ▶use Import::Into;
Subroutine BEGIN: called CC=1 SCAR=0.0
58 # Use Import::Into to export classes into caller
59 15 ▶sub import {
Subroutine import: called CC=1 SCAR=0.0
60 15 my $target = caller;
61 15 Algorithm::AM::BigInt->import::into($target, 'bigcmp');
62 15 Algorithm::AM::DataSet->import::into($target, 'dataset_from_file');
63 15 Algorithm::AM::DataSet::Item->import::into($target, 'new_item');
64 15 return;
65 }
66  
67 10 require XSLoader;
68 10 XSLoader::load(__PACKAGE__, $VERSION);
69  
70 10 ▶use Log::Any qw($log);
Subroutine BEGIN: called CC=1 SCAR=0.0
71  
72 # do all of the classification data structure initialization here,
73 # as well as calling the XS initialization method.
74 192 ▶sub _initialize {
Subroutine _initialize: called CC=2 SCAR=6.9
75 192 my ($self) = @_;
76  
77 192 my $train = $self->training_set;
78  
79 # compute sub-lattices sizes here so that lattice space can be
80 # allocated in the _xs_initialize method. If certain features are
81 # thrown out later, each sub-lattice can only get smaller, so
82 # this is safe to do once here.
83 192 my $lattice_sizes = _compute_lattice_sizes($train->cardinality);
84  
85 # sum is intitialized to a list of zeros
86 192 @{$self->{sum}} = (0.0) x ($train->num_classes + 1);
87  
88 # preemptively allocate memory
89 # TODO: not sure what this does
90 192 @{$self->{itemcontextchain}} = (0) x $train->size;
91  
92 192 $self->{$_} = {} for (
93 qw(
94 itemcontextchainhead
95 context_to_class
96 context_size
97 pointers
98 raw_gang
99 )
100 );
101  
102 # Initialize XS data structures
103 # TODO: Perl crashes unless this is saved. The XS
104 # must not be increasing the reference count
105 192 $self->{save_this} = $train->_data_classes;
106 $self->_xs_initialize(
107 $lattice_sizes,
108 $self->{save_this},
109 $self->{itemcontextchain},
110 $self->{itemcontextchainhead},
111 $self->{context_to_class},
112 $self->{context_size},
113 $self->{pointers},
114 $self->{raw_gang},
115 $self->{sum}
116 192 );
117 192 return;
118 }
119  
120 195 ▶sub classify {
Subroutine classify: called CC=14 SCAR=26.4
Pod documented
121 195 my ($self, $test_item) = @_;
122  
123 195 my $training_set = $self->training_set;
124 195 ▶ if($training_set->cardinality != $test_item->cardinality){
Branch: 1 branch
BranchTrueFalseTotal
if ($training_set->cardinality != $test_item->cardinality) 1 194 195
125 1 croak 'Training set and test item do not have the same ' .
126 'cardinality (' . $training_set->cardinality . ' and ' .
127 $test_item->cardinality . ')';
128 }
129  
130 # num_feats is the number of features to be used in classification;
131 # if we exclude nulls, then we need to minus the number of '='
132 # found in this test item; otherwise, it's just the number of
133 # columns in a single item vector
134 194 my $num_feats = $training_set->cardinality;
135  
136 194 ▶ if($self->exclude_nulls){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->exclude_nulls) 189 5 194
137 1808 $num_feats -= grep {$_ eq ''} @{
138 189 $test_item->features };
139 }
140  
141 # recalculate the lattice sizes with new number of active features
142 194 my $lattice_sizes = _compute_lattice_sizes($num_feats);
143 ## $activeContexts = 1 << $activeVar;
144  
145 194 my $nullcontext = pack "b64", '0' x 64;
146  
147 194 my $given_excluded = 0;
148 194 my $test_in_training = 0;
149  
150 # initialize classification-related variables
151 # it is important to dereference rather than just
152 # assigning a new one with [] or {}. This is because
153 # the XS code has access to the existing reference,
154 # but will be accessing the wrong variable if we
155 # change it.
156 194 %{$self->{context_size}} = ();
157 194 %{$self->{itemcontextchainhead}} = ();
158 194 %{$self->{context_to_class}} = ();
159 194 %{$self->{pointers}} = ();
160 194 %{$self->{raw_gang}} = ();
161 194 @{$self->{itemcontextchain}} = ();
162 # big ints are used in AM.xs; these consist of an
163 # array of 8 unsigned longs
164 194 foreach (@{$self->{sum}}) {
165 753 $_ = pack "L!8", 0, 0, 0, 0, 0, 0, 0, 0;
166 }
167  
168 # calculate context labels and associated structures for
169 # the entire data set
170 194 for my $index ( 0 .. $training_set->size - 1 ) {
171 my $context = _context_label(
172 # Note: this must be copied to prevent infinite loop;
173 # see todo note for _context_label
174 30034 [@{$lattice_sizes}],
175 $training_set->get_item($index)->features,
176 $test_item->features,
177 $self->exclude_nulls
178 );
179 30034 $self->{context_size}->{$context}++;
180 # TODO: explain itemcontextchain and itemcontextchainhead
181 $self->{itemcontextchain}->[$index] =
182 30034 $self->{itemcontextchainhead}->{$context};
183 30034 $self->{itemcontextchainhead}->{$context} = $index;
184  
185 # store the class for the subcontext; if there
186 # is already a different class for this subcontext,
187 # then store 0, signifying heterogeneity.
188 30034 my $class = $training_set->_index_for_class(
189 $training_set->get_item($index)->class);
190 30034 ▶ if ( defined $self->{context_to_class}->{$context} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'context_to_class'}{$context}) { } 21669 8365 30034
191 21669 ▶ if($self->{context_to_class}->{$context} != $class){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"context_to_class"}{$context} != $class) 9834 11835 21669
192 9834 $self->{context_to_class}->{$context} = 0;
193 }
194 }
195 else {
196 8365 $self->{context_to_class}->{$context} = $class;
197 }
198 }
199 # $nullcontext is all 0's, which is a context label for
200 # a training item that exactly matches the test item. Exclude
201 # the item if required, and set a flag that the test item was
202 # found in the training set.
203 194 ▶ if ( exists $self->{context_to_class}->{$nullcontext} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"context_to_class"}{$nullcontext}) 182 12 194
204 182 $test_in_training = 1;
205 182 ▶ if($self->exclude_given){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->exclude_given) 177 5 182
206 177 delete $self->{context_to_class}->{$nullcontext};
207 177 $given_excluded = 1;
208 }
209 }
210 # initialize the results object to hold all of the configuration
211 # info.
212 194 ▶ my $result = Algorithm::AM::Result->new(
Branch: 1 branch
BranchTrueFalseTotal
$self->linear ? : 5 189 194
213 given_excluded => $given_excluded,
214 cardinality => $num_feats,
215 exclude_nulls => $self->exclude_nulls,
216 count_method => $self->linear ? 'linear' : 'squared',
217 training_set => $training_set,
218 test_item => $test_item,
219 test_in_train => $test_in_training,
220 );
221  
222 0 ▶ $log->debug(${$result->config_info})
Branch: 1 branch
BranchTrueFalseTotal
if $Algorithm::AM::log->is_debug 0 194 194
223 if($log->is_debug);
224  
225 194 $result->start_time([ (localtime)[0..2] ]);
226 194 ▶ $self->_fillandcount(
Branch: 1 branch
BranchTrueFalseTotal
$self->linear ? : 5 189 194
227 $lattice_sizes, $self->linear ? 1 : 0);
228 194 $result->end_time([ (localtime)[0..2] ]);
229  
230 194 ▶ unless ($self->{pointers}->{'grand_total'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"pointers"}{"grand_total"}) 1 193 194
231 #TODO: is this tested yet?
232 1 ▶ if($log->is_warn){
Branch: 1 branch
BranchTrueFalseTotal
if ($Algorithm::AM::log->is_warn) 0 1 1
233 0 $log->warn('No training items considered. ' .
234 'No prediction possible.');
235 }
236 1 return;
237 }
238  
239 $result->_process_stats(
240 # TODO: after refactoring to a "guts" object,
241 # just pass that in
242 $self->{sum},
243 $self->{pointers},
244 $self->{itemcontextchainhead},
245 $self->{itemcontextchain},
246 $self->{context_to_class},
247 $self->{raw_gang},
248 $lattice_sizes,
249 $self->{context_size}
250 193 );
251 193 return $result;
252 }
253  
254 # since we split the lattice in four, we have to decide which features
255 # go where. Given the number of features being used, return an arrayref
256 # containing the number of features to be used in each of the the four
257 # lattices.
258 386 ▶sub _compute_lattice_sizes {
Subroutine _compute_lattice_sizes: called CC=1 SCAR=0.0
259 386 my ($num_feats) = @_;
260  
261 10 ▶ use integer;
Subroutine BEGIN: called CC=1 SCAR=0.0
262 386 my @lattice_sizes;
263 386 my $half = $num_feats / 2;
264 386 $lattice_sizes[0] = $half / 2;
265 386 $lattice_sizes[1] = $half - $lattice_sizes[0];
266 386 $half = $num_feats - $half;
267 386 $lattice_sizes[2] = $half / 2;
268 386 $lattice_sizes[3] = $half - $lattice_sizes[2];
269 386 return \@lattice_sizes;
270 }
271  
272 # Create binary context labels for a training item
273 # by comparing it with a test item. Each training item
274 # needs one binary label for each sublattice (of which
275 # there are currently four), but this is packed into a
276 # single scalar representing an array of 4 shorts (this
277 # format is used in the XS side).
278  
279 # TODO: we have to copy lattice_sizes out of $self in order to
280 # iterate it. Otherwise it goes on forever. Why?
281 30034 ▶sub _context_label {
Subroutine _context_label: called CC=5 SCAR=16.1
282 # inputs:
283 # number of active features in each lattice,
284 # training item features, test item features,
285 # and boolean indicating if nulls should be excluded
286 30034 my ($lattice_sizes, $train_feats, $test_feats, $skip_nulls) = @_;
287  
288 # feature index
289 30034 my $index = 0;
290 # the binary context labels for each separate lattice
291 30034 my @context_list = ();
292  
293 30034 for my $a (@$lattice_sizes) {
294 # binary context label for a single sublattice
295 120136 my $context = 0;
296 # loop through all features in the sublattice
297 # assign 0 if features match, 1 if they do not
298 120136 ▶ for ( ; $a ; --$a ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a) 247274 120136 367410
299  
300 # skip null features if indicated
301 247274 ▶ if($skip_nulls){
Branch: 1 branch
BranchTrueFalseTotal
if ($skip_nulls) 247187 87 247274
302 247187 ▶ ++$index while $test_feats->[$index] eq '';
Branch: 1 branch
BranchTrueFalseTotal
$test_feats->[$index] eq "" and do { ++$index } 52442 247187 299629
303 }
304 # add a 1 for mismatched variable, 0 for matched variable
305 247274 $context = ( $context << 1 ) | (
306 $test_feats->[$index] ne $train_feats->[$index] );
307 247274 ++$index;
308 }
309 120136 push @context_list, $context;
310 }
311 # a context label is an array of unsigned shorts in XS
312 30034 my $context = pack "S!4", @context_list;
313 30034 return $context;
314 }
315  
316 10 1;
317  
318 __END__
« blib/lib/Algorithm/AM/Batch.pm ↑ Summary blib/lib/Algorithm/AM/Result.pm »