| 1 | use strict; | ||
| 2 | use warnings; | ||
| 3 | |||
| 4 | package AI::MaxEntropy::Util; | ||
| 5 | |||
| 6 | use Exporter; | ||
| 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 | my ($code, $samples, $pattern, $t) = @_; | ||
| 20 | $t ||= 'x'; | ||
| 21 | my ($p, $n) = (length($pattern), scalar(@$samples)); | ||
| 22 | for my $i (grep { substr($pattern, $_, 1) eq $t } (0 .. $p - 1)) { | ||
| 23 | for (int($n * $i / $p) .. int($n * ($i + 1) / $p) - 1) { | ||
| 24 | $_ = $samples->[$_]; | ||
| 25 | $code->(); | ||
| 26 | } | ||
| 27 | } | ||
| 28 | } | ||
| 29 | |||
| 30 | sub map_partially(&$$;$) { | ||
| 31 | my ($code, $samples, $pattern, $t) = @_; | ||
| 32 | my @r; | ||
| 33 | traverse_partially { push @r, $code->($_) } $samples, $pattern, $t; | ||
| 34 | return \@r; | ||
| 35 | } | ||
| 36 | |||
| 37 | sub train_and_test { | ||
| 38 | my ($me, $samples, $pattern) = @_; | ||
| 39 | traverse_partially { $me->see(@$_) } $samples, $pattern, 'x'; | ||
| 40 | my $m = $me->learn; | ||
| 41 | my $r = map_partially { [$_ => $m->predict($_->[0])] } | ||
| 42 | $samples, $pattern, 'o'; | ||
| 43 | return ($r, $m); | ||
| 44 | } | ||
| 45 | |||
| 46 | sub precision { | ||
| 47 | my $r = shift; | ||
| 48 | my ($c, $n) = (0, 0); | ||
| 49 | for (@$r) { | ||
| 50 | my $w = defined($_->[0]->[2]) ? $_->[0]->[2] : 1; | ||
| 51 | $n += $w; | ||
| 52 | $c += $w if $_->[0]->[1] eq $_->[1]; | ||
| 53 | } | ||
| 54 | return $c / $n; | ||
| 55 | } | ||
| 56 | |||
| 57 | sub recall { | ||
| 58 | my $r = shift; | ||
| 59 | my $label = shift; | ||
| 60 | my ($c, $n) = (0, 0); | ||
| 61 | for (@$r) { | ||
| 62 | if ($_->[0]->[1] eq $label) { | ||
| 63 | my $w = defined($_->[0]->[2]) ? $_->[0]->[2] : 1; | ||
| 64 | $n += $w; | ||
| 65 | $c += $w if $_->[1] eq $label; | ||
| 66 | } | ||
| 67 | } | ||
| 68 | return $c / $n; | ||
| 69 | } | ||
| 70 | |||
| 71 | 1; | ||
| 72 | |||
| 73 | __END__ |