File Coverage

blib/lib/AI/MaxEntropy/Util.pm
Criterion Covered Total %
statement 45 45 100.0
branch 9 10 90.0
condition 2 2 100.0
subroutine 11 11 100.0
pod 5 5 100.0
total 72 73 98.6


line stmt bran cond sub pod time code
1 1     1   6 use strict;
  1         2  
  1         33  
2 1     1   6 use warnings;
  1         2  
  1         50  
3              
4             package AI::MaxEntropy::Util;
5              
6 1     1   6 use Exporter;
  1         2  
  1         726  
7              
8             our $VERSION = '0.20';
9              
10             our @ISA = qw/Exporter/;
11              
12             our @EXPORT_OK =
13             qw/traverse_partially map_partially train_and_test precision recall/;
14              
15             our %EXPORT_TAGS =
16             (all => [@EXPORT_OK]);
17              
18             sub traverse_partially(&$$;$) {
19 7     7 1 53 my ($code, $samples, $pattern, $t) = @_;
20 7   100     41 $t ||= 'x';
21 7         15 my ($p, $n) = (length($pattern), scalar(@$samples));
22 7         23 for my $i (grep { substr($pattern, $_, 1) eq $t } (0 .. $p - 1)) {
  29         70  
23 16         73 for (int($n * $i / $p) .. int($n * ($i + 1) / $p) - 1) {
24 20         45 $_ = $samples->[$_];
25 20         40 $code->();
26             }
27             }
28             }
29              
30             sub map_partially(&$$;$) {
31 3     3 1 22 my ($code, $samples, $pattern, $t) = @_;
32 3         6 my @r;
33 3     7   21 traverse_partially { push @r, $code->($_) } $samples, $pattern, $t;
  7         15  
34 3         20 return \@r;
35             }
36              
37             sub train_and_test {
38 2     2 1 87 my ($me, $samples, $pattern) = @_;
39 2     6   18 traverse_partially { $me->see(@$_) } $samples, $pattern, 'x';
  6         22  
40 2         14 my $m = $me->learn;
41 3     3   15 my $r = map_partially { [$_ => $m->predict($_->[0])] }
42 2         12 $samples, $pattern, 'o';
43 2         12 return ($r, $m);
44             }
45              
46             sub precision {
47 1     1 1 10 my $r = shift;
48 1         2 my ($c, $n) = (0, 0);
49 1         3 for (@$r) {
50 2 100       8 my $w = defined($_->[0]->[2]) ? $_->[0]->[2] : 1;
51 2         3 $n += $w;
52 2 100       10 $c += $w if $_->[0]->[1] eq $_->[1];
53             }
54 1         8 return $c / $n;
55             }
56              
57             sub recall {
58 1     1 1 2 my $r = shift;
59 1         2 my $label = shift;
60 1         3 my ($c, $n) = (0, 0);
61 1         2 for (@$r) {
62 2 50       8 if ($_->[0]->[1] eq $label) {
63 2 100       7 my $w = defined($_->[0]->[2]) ? $_->[0]->[2] : 1;
64 2         4 $n += $w;
65 2 100       8 $c += $w if $_->[1] eq $label;
66             }
67             }
68 1         6 return $c / $n;
69             }
70              
71             1;
72              
73             __END__