Categorizer/KnowledgeSet.pm

filter: Statementstmt 45.5% 103 / 226 Branchbran 35.7% 30 / 84 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 55.0% 22 / 40 Podpod 78.2% 18 / 23 totaltotal 44.5% 173 / 388 CC 64 SCAR 29.7
CC
64
Cov
42%
scan_stats
56.0
restore_features
56.0
weigh_features
35.8
CRAP 19.4
« Categorizer/FeatureSelector/CategorySelector.pm ↑ Summary Categorizer/FeatureSelector.pm »
1 package AI::Categorizer::KnowledgeSet;
2  
3 11 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 11 ▶use Class::Container;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 11 ▶use AI::Categorizer::Storable;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 11 ▶use base qw(Class::Container AI::Categorizer::Storable);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 11 ▶use Params::Validate qw(:types);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 11 ▶use AI::Categorizer::ObjectSet;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 11 ▶use AI::Categorizer::Document;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 11 ▶use AI::Categorizer::Category;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 11 ▶use AI::Categorizer::FeatureVector;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 11 ▶use AI::Categorizer::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 11 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 __PACKAGE__->valid_params
17 (
18 categories => {
19 type => ARRAYREF,
20 default => [],
21 callbacks => { 'all are Category objects' =>
22 1 ▶ sub { ! grep !UNIVERSAL::isa($_, 'AI::Categorizer::Category'),
Subroutine __ANON__: called CC=1 SCAR=0.0
23 1 @{$_[0]} },
24 },
25 },
26 documents => {
27 type => ARRAYREF,
28 default => [],
29 callbacks => { 'all are Document objects' =>
30 0 ▶ sub { ! grep !UNIVERSAL::isa($_, 'AI::Categorizer::Document'),
Subroutine __ANON__: not called CC=1 SCAR=6.9
31 0 @{$_[0]} },
32 },
33 },
34 11 scan_first => {
35 type => BOOLEAN,
36 default => 1,
37 },
38 feature_selector => {
39 isa => 'AI::Categorizer::FeatureSelector',
40 },
41 tfidf_weighting => {
42 type => SCALAR,
43 optional => 1,
44 },
45 term_weighting => {
46 type => SCALAR,
47 default => 'x',
48 },
49 collection_weighting => {
50 type => SCALAR,
51 default => 'x',
52 },
53 normalize_weighting => {
54 type => SCALAR,
55 default => 'x',
56 },
57 verbose => {
58 type => SCALAR,
59 default => 0,
60 },
61 );
62  
63 11 __PACKAGE__->contained_objects
64 (
65 document => { delayed => 1,
66 class => 'AI::Categorizer::Document' },
67 category => { delayed => 1,
68 class => 'AI::Categorizer::Category' },
69 collection => { delayed => 1,
70 class => 'AI::Categorizer::Collection::Files' },
71 features => { delayed => 1,
72 class => 'AI::Categorizer::FeatureVector' },
73 feature_selector => 'AI::Categorizer::FeatureSelector::DocFrequency',
74 );
75  
76 12 ▶sub new {
Subroutine new: called CC=4 SCAR=14.9
Pod documented
77 12 my ($pkg, %args) = @_;
78
79 # Shortcuts
80 12 ▶ if ($args{tfidf_weighting}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"tfidf_weighting"}) 1 11 12
81 1 @args{'term_weighting', 'collection_weighting', 'normalize_weighting'} = split '', $args{tfidf_weighting};
82 1 delete $args{tfidf_weighting};
83 }
84  
85 12 my $self = $pkg->SUPER::new(%args);
86  
87 # Convert to AI::Categorizer::ObjectSet sets
88 12 $self->{categories} = new AI::Categorizer::ObjectSet( @{$self->{categories}} );
89 12 $self->{documents} = new AI::Categorizer::ObjectSet( @{$self->{documents}} );
90  
91 12 ▶ if ($self->{load}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"load"}) 0 12 12
92 0 ▶ my $args = ref($self->{load}) ? $self->{load} : { path => $self->{load} };
Branch: 1 branch
BranchTrueFalseTotal
ref $self->{'load'} ? : 0 0 0
93 0 $self->load(%$args);
94 0 delete $self->{load};
95 }
96 12 return $self;
97 }
98  
99 19 ▶sub features {
Subroutine features: called CC=5 SCAR=16.1
Pod documented
100 19 my $self = shift;
101  
102 19 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 1 18 19
103 1 $self->{features} = shift;
104 1 ▶ $self->trim_doc_features if $self->{features};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"features"} 0 1 1
105 }
106 19 ▶ return $self->{features} if $self->{features};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"features"} 16 3 19
107  
108 # Create a feature vector encompassing the whole set of documents
109 3 my $v = $self->create_delayed_object('features');
110 3 foreach my $document ($self->documents) {
111 12 $v->add( $document->features );
112 }
113 3 return $self->{features} = $v;
114 }
115  
116 24 ▶sub categories {
Subroutine categories: called CC=2 SCAR=7.2
Pod documented
117 24 my $c = $_[0]->{categories};
118 24 ▶ return wantarray ? $c->members : $c->size;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 24 0 24
119 }
120  
121 35 ▶sub documents {
Subroutine documents: called CC=2 SCAR=6.9
Pod documented
122 35 my $d = $_[0]->{documents};
123 35 ▶ return wantarray ? $d->members : $d->size;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 32 3 35
124 }
125  
126 7 ▶sub document {
Subroutine document: called CC=1 SCAR=0.0
Pod documented
127 7 my ($self, $name) = @_;
128 7 return $self->{documents}->retrieve($name);
129 }
130  
131 0 ▶sub feature_selector { $_[0]->{feature_selector} }
Subroutine feature_selector: not called CC=1 SCAR=6.9
Pod undocumented
132 0 ▶sub scan_first { $_[0]->{scan_first} }
Subroutine scan_first: not called CC=1 SCAR=6.9
Pod undocumented
133  
134 0 ▶sub verbose {
Subroutine verbose: not called CC=2 SCAR=17.9
Pod documented
135 0 my $self = shift;
136 0 ▶ $self->{verbose} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 0 0
137 0 return $self->{verbose};
138 }
139  
140 0 ▶sub trim_doc_features {
Subroutine trim_doc_features: not called CC=2 SCAR=17.9
Pod undocumented
141 0 my ($self) = @_;
142
143 0 foreach my $doc ($self->documents) {
144 0 $doc->features( $doc->features->intersection($self->features) );
145 }
146 }
147  
148  
149 0 ▶sub prog_bar {
Subroutine prog_bar: not called CC=4 SCAR=30.0
Pod undocumented
150 0 my ($self, $collection) = @_;
151  
152 0 ▶ return sub {} unless $self->verbose;
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless $self->verbose 0 0 0
153 0 ▶ return sub { print STDERR '.' } unless eval "use Time::Progress; 1";
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless eval "use Time::Progress; 1" 0 0 0
154  
155 0 ▶ my $count = $collection->can('count_documents') ? $collection->count_documents : 0;
Branch: 1 branch
BranchTrueFalseTotal
$collection->can('count_documents') ? : 0 0 0
156
157 0 my $pb = 'Time::Progress'->new;
158 0 $pb->attr(max => $count);
159 0 my $i = 0;
160 0 ▶ return sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
161 0 $i++;
162 0 ▶ return if $i % 25;
Branch: 1 branch
BranchTrueFalseTotal
if $i % 25 0 0 0
163 0 print STDERR $pb->report("%50b %p ($i/$count)\r", $i);
164 0 };
165 }
166  
167 # A little utility method for several other methods like scan_stats(),
168 # load(), read(), etc.
169 0 ▶sub _make_collection {
Subroutine _make_collection: not called CC=2 SCAR=17.9
170 0 my ($self, $args) = @_;
171 0 ▶ return $args->{collection} || $self->create_delayed_object('collection', %$args);
Condition0%0/3
$args->{'collection'} || $self->create_delayed_object('collection', %$args)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{'collection'} || $self->create_delayed_object('collection', %$args)
$args->{'collection'} $self->create_delayed_object('collection', %$args)
Truth table0%0/3
A || B
A= $args->{'collection'}B= $self->create_delayed_object('collection', %$args)
ABresult
1X1
011
000
172 }
173  
174 0 ▶sub scan_stats {
Subroutine scan_stats: not called CC=7 SCAR=40.3
Pod documented
175 # Should determine:
176 # - number of documents
177 # - number of categories
178 # - avg. number of categories per document (whole corpus)
179 # - avg. number of tokens per document (whole corpus)
180 # - avg. number of types per document (whole corpus)
181 # - number of documents, tokens, & types for each category
182 # - "category skew index" (% variance?) by num. documents, tokens, and types
183  
184 0 my ($self, %args) = @_;
185 0 my $collection = $self->_make_collection(\%args);
186 0 my $pb = $self->prog_bar($collection);
187  
188 0 my %stats;
189  
190  
191 0 ▶ while (my $doc = $collection->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $doc = $collection->next) 0 0 0
192 0 $pb->();
193 0 $stats{category_count_with_duplicates} += $doc->categories;
194  
195 0 my ($sum, $length) = ($doc->features->sum, $doc->features->length);
196 0 $stats{document_count}++;
197 0 $stats{token_count} += $sum;
198 0 $stats{type_count} += $length;
199
200 0 foreach my $cat ($doc->categories) {
201 #warn $doc->name, ": ", $cat->name, "\n";
202 0 $stats{categories}{$cat->name}{document_count}++;
203 0 $stats{categories}{$cat->name}{token_count} += $sum;
204 0 $stats{categories}{$cat->name}{type_count} += $length;
205 }
206 }
207 0 ▶ print "\n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 0 0
208  
209 0 my @cats = keys %{ $stats{categories} };
210  
211 0 $stats{category_count} = @cats;
212 0 $stats{categories_per_document} = $stats{category_count_with_duplicates} / $stats{document_count};
213 0 $stats{tokens_per_document} = $stats{token_count} / $stats{document_count};
214 0 $stats{types_per_document} = $stats{type_count} / $stats{document_count};
215  
216 0 foreach my $thing ('type', 'token', 'document') {
217 $stats{"${thing}s_per_category"} = AI::Categorizer::Util::average
218 0 ( map { $stats{categories}{$_}{"${thing}_count"} } @cats );
219  
220 0 ▶ next unless @cats;
Branch: 1 branch
BranchTrueFalseTotal
unless @cats 0 0 0
221  
222 # Compute the skews
223 0 my $ssum;
224 0 foreach my $cat (@cats) {
225 0 $ssum += ($stats{categories}{$cat}{"${thing}_count"} - $stats{"${thing}s_per_category"}) ** 2;
226 }
227 0 $stats{"${thing}_skew_by_category"} = sqrt($ssum/@cats) / $stats{"${thing}s_per_category"};
228 }
229  
230 0 return \%stats;
231 }
232  
233 0 ▶sub load {
Subroutine load: not called CC=3 SCAR=24.8
Pod documented
234 0 my ($self, %args) = @_;
235 0 my $c = $self->_make_collection(\%args);
236  
237 0 ▶ if ($self->{features_kept}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'features_kept'}) { } 0 0 0
elsif ($self->{'scan_first'}) { } 0 0 0
238 # Read the whole thing in, then reduce
239 0 $self->read( collection => $c );
240 0 $self->select_features;
241  
242 } elsif ($self->{scan_first}) {
243 # Figure out the feature set first, then read data in
244 0 $self->scan_features( collection => $c );
245 0 $c->rewind;
246 0 $self->read( collection => $c );
247  
248 } else {
249 # Don't do any feature reduction, just read the data
250 0 $self->read( collection => $c );
251 }
252 }
253  
254 0 ▶sub read {
Subroutine read: not called CC=3 SCAR=24.8
Pod documented
255 0 my ($self, %args) = @_;
256 0 my $collection = $self->_make_collection(\%args);
257 0 my $pb = $self->prog_bar($collection);
258
259 0 ▶ while (my $doc = $collection->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $doc = $collection->next) 0 0 0
260 0 $pb->();
261 0 $self->add_document($doc);
262 }
263 0 ▶ print "\n" if $self->verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $self->verbose 0 0 0
264 }
265  
266 11 ▶sub finish {
Subroutine finish: called CC=2 SCAR=6.9
Pod documented
267 11 my $self = shift;
268 11 ▶ return if $self->{finished}++;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"finished"}++ 1 10 11
269 10 $self->weigh_features;
270 }
271  
272 10 ▶sub weigh_features {
Subroutine weigh_features: called CC=20 SCAR=35.8
Pod documented
273 # This could be made more efficient by figuring out an execution
274 # plan in advance
275  
276 10 my $self = shift;
277
278 10 ▶ if ( $self->{term_weighting} =~ /^(t|x)$/ ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($self->{'term_weighting'} =~ /^(t|x)$/) { } 8 2 10
elsif ($self->{'term_weighting'} eq 'l') { } 0 2 2
elsif ($self->{'term_weighting'} eq 'n') { } 1 1 2
elsif ($self->{'term_weighting'} eq 'b') { } 1 0 1
279 # Nothing to do
280 } elsif ( $self->{term_weighting} eq 'l' ) {
281 0 foreach my $doc ($self->documents) {
282 0 my $f = $doc->features->as_hash;
283 0 $_ = 1 + log($_) foreach values %$f;
284 }
285 } elsif ( $self->{term_weighting} eq 'n' ) {
286 1 foreach my $doc ($self->documents) {
287 4 my $f = $doc->features->as_hash;
288 4 my $max_tf = AI::Categorizer::Util::max values %$f;
289 4 $_ = 0.5 + 0.5 * $_ / $max_tf foreach values %$f;
290 }
291 } elsif ( $self->{term_weighting} eq 'b' ) {
292 1 foreach my $doc ($self->documents) {
293 4 my $f = $doc->features->as_hash;
294 4 ▶ $_ = $_ ? 1 : 0 foreach values %$f;
Branch: 1 branch
BranchTrueFalseTotal
$_ ? : 26 0 26
295 }
296 } else {
297 0 die "term_weighting must be one of 'x', 't', 'l', 'b', or 'n'";
298 }
299
300 10 ▶ if ($self->{collection_weighting} eq 'x') {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'collection_weighting'} eq 'x') { } 9 1 10
elsif ($self->{'collection_weighting'} =~ /^(f|p)$/) { } 1 0 1
301 # Nothing to do
302 } elsif ($self->{collection_weighting} =~ /^(f|p)$/) {
303 1 ▶ my $subtrahend = ($1 eq 'f' ? 0 : 1);
Branch: 1 branch
BranchTrueFalseTotal
$1 eq 'f' ? : 1 0 1
304 1 my $num_docs = $self->documents;
305 1 $self->document_frequency('foo'); # Initialize
306 1 foreach my $doc ($self->documents) {
307 4 my $f = $doc->features->as_hash;
308 4 $f->{$_} *= log($num_docs / $self->{doc_freq_vector}{$_} - $subtrahend) foreach keys %$f;
309 }
310 } else {
311 0 die "collection_weighting must be one of 'x', 'f', or 'p'";
312 }
313  
314 10 ▶ if ( $self->{normalize_weighting} eq 'x' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'normalize_weighting'} eq 'x') { } 10 0 10
elsif ($self->{'normalize_weighting'} eq 'c') { } 0 0 0
315 # Nothing to do
316 } elsif ( $self->{normalize_weighting} eq 'c' ) {
317 0 $_->features->normalize foreach $self->documents;
318 } else {
319 0 die "normalize_weighting must be one of 'x' or 'c'";
320 }
321 }
322  
323 4 ▶sub document_frequency {
Subroutine document_frequency: called CC=5 SCAR=16.1
Pod documented
324 4 my ($self, $term) = @_;
325
326 4 ▶ unless (exists $self->{doc_freq_vector}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"doc_freq_vector"}) 1 3 4
327 1 ▶ die "No corpus has been scanned for features" unless $self->documents;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->documents 0 1 1
328  
329 1 my $doc_freq = $self->create_delayed_object('features', features => {});
330 1 foreach my $doc ($self->documents) {
331 4 $doc_freq->add( $doc->features->as_boolean_hash );
332 }
333 1 $self->{doc_freq_vector} = $doc_freq->as_hash;
334 }
335
336 4 ▶ return exists $self->{doc_freq_vector}{$term} ? $self->{doc_freq_vector}{$term} : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $self->{'doc_freq_vector'}{$term} ? : 3 1 4
337 }
338  
339 0 ▶sub scan_features {
Subroutine scan_features: not called CC=1 SCAR=6.9
Pod documented
340 0 my ($self, %args) = @_;
341 0 my $c = $self->_make_collection(\%args);
342  
343 0 my $pb = $self->prog_bar($c);
344 0 my $ranked_features = $self->{feature_selector}->scan_features( collection => $c, prog_bar => $pb );
345  
346 0 $self->delayed_object_params('document', use_features => $ranked_features);
347 0 $self->delayed_object_params('collection', use_features => $ranked_features);
348 0 return $ranked_features;
349 }
350  
351 0 ▶sub select_features {
Subroutine select_features: not called CC=1 SCAR=6.9
Pod undocumented
352 0 my $self = shift;
353
354 0 my $f = $self->feature_selector->select_features(knowledge_set => $self);
355 0 $self->features($f);
356 }
357  
358 0 ▶sub partition {
Subroutine partition: not called CC=3 SCAR=24.8
Pod documented
359 0 my ($self, @sizes) = @_;
360 0 my $num_docs = my @docs = $self->documents;
361 0 my @groups;
362  
363 0 ▶ while (@sizes > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sizes > 1) 0 0 0
364 0 my $size = int ($num_docs * shift @sizes);
365 0 push @groups, [];
366 0 for (0..$size) {
367 0 push @{ $groups[-1] }, splice @docs, rand(@docs), 1;
368 }
369 }
370 0 push @groups, \@docs;
371  
372 0 return map { ref($self)->new( documents => $_ ) } @groups;
373 }
374  
375 40 ▶sub make_document {
Subroutine make_document: called CC=1 SCAR=0.0
Pod documented
376 40 my ($self, %args) = @_;
377 40 my $cats = delete $args{categories};
378 40 my @cats = map { $self->call_method('category', 'by_name', name => $_) } @$cats;
379 40 my $d = $self->create_delayed_object('document', %args, categories => \@cats);
380 40 $self->add_document($d);
381 }
382  
383 40 ▶sub add_document {
Subroutine add_document: called CC=2 SCAR=6.9
Pod documented
384 40 my ($self, $doc) = @_;
385  
386 40 foreach ($doc->categories) {
387 40 $_->add_document($doc);
388 }
389 40 $self->{documents}->insert($doc);
390 40 $self->{categories}->insert($doc->categories);
391 }
392  
393 0 ▶sub save_features {
Subroutine save_features: not called CC=5 SCAR=34.0
Pod documented
394 0 my ($self, $file) = @_;
395
396 my $f = ($self->{features} || { $self->delayed_object_params('document') }->{use_features})
397 0 ▶ or croak "No features to save";
Branch: 1 branch
BranchTrueFalseTotal
my $f = $self->{"features"} || {$self->delayed_object_params("document")}->{"use_features"} or croak("No features to save") 0 0 0
Condition0%0/3
$self->{'features'} || {$self->delayed_object_params('document')}->{'use_features'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{'features'} || {$self->delayed_object_params('document')}->{'use_features'}
$self->{'features'} {$self->delayed_object_params('document')}->{'use_features'}
Truth table0%0/3
A || B
A= $self->{'features'}B= {$self->delayed_object_params('document')}->{'use_features'}
ABresult
1X1
011
000
398
399 0 ▶ open my($fh), "> $file" or croak "Can't create $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "> $file" or croak("Can't create ${file}: $!") 0 0 0
400 0 my $h = $f->as_hash;
401 0 print $fh "# Total: ", $f->length, "\n";
402
403 0 foreach my $k (sort {$h->{$b} <=> $h->{$a}} keys %$h) {
404 0 print $fh "$k\t$h->{$k}\n";
405 }
406 0 close $fh;
407 }
408  
409 0 ▶sub restore_features {
Subroutine restore_features: not called CC=7 SCAR=40.3
Pod documented
410 0 my ($self, $file, $n) = @_;
411
412 0 ▶ open my($fh), "< $file" or croak "Can't open $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "< $file" or croak("Can't open ${file}: $!") 0 0 0
413  
414 0 my %hash;
415 0 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 0 0 0
416 0 ▶ next if /^#/;
Branch: 1 branch
BranchTrueFalseTotal
if /^#/ 0 0 0
417 0 ▶ /^(.*)\t([\d.]+)$/ or croak "Malformed line: $_";
Branch: 1 branch
BranchTrueFalseTotal
/^(.*)\t([\d.]+)$/ or croak("Malformed line: $_") 0 0 0
418 0 $hash{$1} = $2;
419 0 ▶ last if defined $n and $. >= $n;
Branch: 1 branch
BranchTrueFalseTotal
if defined $n and $. >= $n 0 0 0
Condition0%0/3
defined $n and $. >= $n
!ll&&!rl&&r
000
MC/DC0%0/2
defined $n and $. >= $n
defined $n $. >= $n
Truth table0%0/3
A and B
A= defined $nB= $. >= $n
ABresult
0X0
100
111
420 }
421 0 my $features = $self->create_delayed_object('features', features => \%hash);
422
423 0 $self->delayed_object_params('document', use_features => $features);
424 0 $self->delayed_object_params('collection', use_features => $features);
425 }
426  
427 11 1;
428  
429 __END__
« Categorizer/FeatureSelector/CategorySelector.pm ↑ Summary Categorizer/FeatureSelector.pm »