| 1 | package AI::Categorizer::Learner::Weka; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use AI::Categorizer::Learner::Boolean; | ||
| 5 | use base qw(AI::Categorizer::Learner::Boolean); | ||
| 6 | use Params::Validate qw(:types); | ||
| 7 | use File::Spec; | ||
| 8 | use File::Copy; | ||
| 9 | use File::Path (); | ||
| 10 | use File::Temp (); | ||
| 11 | |||
| 12 | __PACKAGE__->valid_params | ||
| 13 | ( | ||
| 14 | java_path => {type => SCALAR, default => 'java'}, | ||
| 15 | java_args => {type => SCALAR|ARRAYREF, optional => 1}, | ||
| 16 | weka_path => {type => SCALAR, optional => 1}, | ||
| 17 | weka_classifier => {type => SCALAR, default => 'weka.classifiers.NaiveBayes'}, | ||
| 18 | weka_args => {type => SCALAR|ARRAYREF, optional => 1}, | ||
| 19 | tmpdir => {type => SCALAR, default => File::Spec->tmpdir}, | ||
| 20 | ); | ||
| 21 | |||
| 22 | __PACKAGE__->contained_objects | ||
| 23 | ( | ||
| 24 | features => {class => 'AI::Categorizer::FeatureVector', delayed => 1}, | ||
| 25 | ); | ||
| 26 | |||
| 27 | sub new { | ||
| 28 | my $class = shift; | ||
| 29 | my $self = $class->SUPER::new(@_); | ||
| 30 | |||
| 31 | for ('java_args', 'weka_args') { | ||
| 32 | $self->{$_} = [] unless defined $self->{$_}; | ||
| 33 | $self->{$_} = [$self->{$_}] unless UNIVERSAL::isa($self->{$_}, 'ARRAY'); | ||
| 34 | } | ||
| 35 | |||
| 36 | if (defined $self->{weka_path}) { | ||
| 37 | push @{$self->{java_args}}, '-classpath', $self->{weka_path}; | ||
| 38 | delete $self->{weka_path}; | ||
| 39 | } | ||
| 40 | return $self; | ||
| 41 | } | ||
| 42 | |||
| 43 | # java -classpath /Applications/Science/weka-3-2-3/weka.jar weka.classifiers.NaiveBayes -t /tmp/train_file.arff -d /tmp/weka-machine | ||
| 44 | |||
| 45 | sub create_model { | ||
| 46 | my ($self) = shift; | ||
| 47 | my $m = $self->{model} ||= {}; | ||
| 48 | $m->{all_features} = [ $self->knowledge_set->features->names ]; | ||
| 49 | $m->{_in_dir} = File::Temp::tempdir( DIR => $self->{tmpdir} ); | ||
| 50 | |||
| 51 | # Create a dummy test file $dummy_file in ARFF format (a kludgey WEKA requirement) | ||
| 52 | my $dummy_features = $self->create_delayed_object('features'); | ||
| 53 | $m->{dummy_file} = $self->create_arff_file("dummy", [[$dummy_features, 0]]); | ||
| 54 | |||
| 55 | $self->SUPER::create_model(@_); | ||
| 56 | } | ||
| 57 | |||
| 58 | sub create_boolean_model { | ||
| 59 | my ($self, $pos, $neg, $cat) = @_; | ||
| 60 | |||
| 61 | my @docs = (map([$_->features, 1], @$pos), | ||
| 62 | map([$_->features, 0], @$neg)); | ||
| 63 | my $train_file = $self->create_arff_file($cat->name . '_train', \@docs); | ||
| 64 | |||
| 65 | my %info = (machine_file => $cat->name . '_model'); | ||
| 66 | my $outfile = File::Spec->catfile($self->{model}{_in_dir}, $info{machine_file}); | ||
| 67 | |||
| 68 | my @args = ($self->{java_path}, | ||
| 69 | @{$self->{java_args}}, | ||
| 70 | $self->{weka_classifier}, | ||
| 71 | @{$self->{weka_args}}, | ||
| 72 | '-t', $train_file, | ||
| 73 | '-T', $self->{model}{dummy_file}, | ||
| 74 | '-d', $outfile, | ||
| 75 | '-v', | ||
| 76 | '-p', '0', | ||
| 77 | ); | ||
| 78 | $self->do_cmd(@args); | ||
| 79 | unlink $train_file or warn "Couldn't remove $train_file: $!"; | ||
| 80 | |||
| 81 | return \%info; | ||
| 82 | } | ||
| 83 | |||
| 84 | # java -classpath /Applications/Science/weka-3-2-3/weka.jar weka.classifiers.NaiveBayes -l out -T test.arff -p 0 | ||
| 85 | |||
| 86 | sub get_boolean_score { | ||
| 87 | my ($self, $doc, $info) = @_; | ||
| 88 | |||
| 89 | # Create document file | ||
| 90 | my $doc_file = $self->create_arff_file('doc', [[$doc->features, 0]], $self->{tmpdir}); | ||
| 91 | my $machine_file = File::Spec->catfile($self->{model}{_in_dir}, $info->{machine_file}); | ||
| 92 | |||
| 93 | my @args = ($self->{java_path}, | ||
| 94 | @{$self->{java_args}}, | ||
| 95 | $self->{weka_classifier}, | ||
| 96 | '-l', $machine_file, | ||
| 97 | '-T', $doc_file, | ||
| 98 | '-p', 0, | ||
| 99 | ); | ||
| 100 | |||
| 101 | my @output = $self->do_cmd(@args); | ||
| 102 | |||
| 103 | my %scores; | ||
| 104 | foreach (@output) { | ||
| 105 | # <doc> <category> <score> <real_category> | ||
| 106 | # 0 large.elem 0.4515551620220952 numberth.high | ||
| 107 | next unless my ($index, $predicted, $score) = /^([\d.]+)\s+(\S+)\s+([\d.]+)/; | ||
| 108 | $scores{$predicted} = $score; | ||
| 109 | } | ||
| 110 | |||
| 111 | return $scores{1} || 0; # Not sure what weka's scores represent... | ||
| 112 | } | ||
| 113 | |||
| 114 | sub categorize_collection { | ||
| 115 | my ($self, %args) = @_; | ||
| 116 | my $c = $args{collection} or die "No collection provided"; | ||
| 117 | |||
| 118 | my @alldocs; | ||
| 119 | while (my $d = $c->next) { | ||
| 120 | push @alldocs, $d; | ||
| 121 | } | ||
| 122 | my $doc_file = $self->create_arff_file("docs", [map [$_->features, 0], @alldocs]); | ||
| 123 | |||
| 124 | my @assigned; | ||
| 125 | |||
| 126 | my $l = $self->{model}{learners}; | ||
| 127 | foreach my $cat (keys %$l) { | ||
| 128 | my $machine_file = File::Spec->catfile($self->{model}{_in_dir}, "${cat}_model"); | ||
| 129 | my @args = ($self->{java_path}, | ||
| 130 | @{$self->{java_args}}, | ||
| 131 | $self->{weka_classifier}, | ||
| 132 | '-l', $machine_file, | ||
| 133 | '-T', $doc_file, | ||
| 134 | '-p', 0, | ||
| 135 | ); | ||
| 136 | |||
| 137 | my @output = $self->do_cmd(@args); | ||
| 138 | |||
| 139 | foreach my $line (@output) { | ||
| 140 | next unless $line =~ /\S/; | ||
| 141 | |||
| 142 | # 0 large.elem 0.4515551620220952 numberth.high | ||
| 143 | unless ( $line =~ /^([\d.]+)\s+(\S+)\s+([\d.]+)\s+(\S+)/ ) { | ||
| 144 | warn "Can't parse line $line"; | ||
| 145 | next; | ||
| 146 | } | ||
| 147 | my ($index, $predicted, $score) = ($1, $2, $3); | ||
| 148 | $assigned[$index]{$cat} = $score if $predicted; # Not sure what weka's scores represent | ||
| 149 | print STDERR "$index: assigned=($predicted) correct=(", $alldocs[$index]->is_in_category($cat) ? 1 : 0, ")\n" | ||
| 150 | if $self->verbose; | ||
| 151 | } | ||
| 152 | } | ||
| 153 | |||
| 154 | my $experiment = $self->create_delayed_object('experiment', categories => [map $_->name, $self->categories]); | ||
| 155 | foreach my $i (0..$#alldocs) { | ||
| 156 | $experiment->add_result([keys %{$assigned[$i]}], [map $_->name, $alldocs[$i]->categories], $alldocs[$i]->name); | ||
| 157 | } | ||
| 158 | |||
| 159 | return $experiment; | ||
| 160 | } | ||
| 161 | |||
| 162 | |||
| 163 | sub do_cmd { | ||
| 164 | my ($self, @cmd) = @_; | ||
| 165 | print STDERR " % @cmd\n" if $self->verbose; | ||
| 166 | |||
| 167 | my @output; | ||
| 168 | local *KID_TO_READ; | ||
| 169 | my $pid = open(KID_TO_READ, "-|"); | ||
| 170 | |||
| 171 | if ($pid) { # parent | ||
| 172 | @output = <KID_TO_READ>; | ||
| 173 | close(KID_TO_READ) or warn "@cmd exited $?"; | ||
| 174 | |||
| 175 | } else { # child | ||
| 176 | exec(@cmd) or die "Can't exec @cmd: $!"; | ||
| 177 | } | ||
| 178 | |||
| 179 | return @output; | ||
| 180 | } | ||
| 181 | |||
| 182 | sub create_arff_file { | ||
| 183 | my ($self, $name, $docs, $dir) = @_; | ||
| 184 | $dir = $self->{model}{_in_dir} unless defined $dir; | ||
| 185 | |||
| 186 | my ($fh, $filename) = File::Temp::tempfile( | ||
| 187 | $name . "_XXXX", # Template | ||
| 188 | DIR => $dir, | ||
| 189 | SUFFIX => '.arff', | ||
| 190 | ); | ||
| 191 | print $fh "\@RELATION foo\n\n"; | ||
| 192 | |||
| 193 | my $feature_names = $self->{model}{all_features}; | ||
| 194 | foreach my $name (@$feature_names) { | ||
| 195 | print $fh "\@ATTRIBUTE feature-$name REAL\n"; | ||
| 196 | } | ||
| 197 | print $fh "\@ATTRIBUTE category {1, 0}\n\n"; | ||
| 198 | |||
| 199 | my %feature_indices = map {$feature_names->[$_], $_} 0..$#{$feature_names}; | ||
| 200 | my $last_index = keys %feature_indices; | ||
| 201 | |||
| 202 | # We use the 'sparse' format, see http://www.cs.waikato.ac.nz/~ml/weka/arff.html | ||
| 203 | |||
| 204 | print $fh "\@DATA\n"; | ||
| 205 | foreach my $doc (@$docs) { | ||
| 206 | my ($features, $cat) = @$doc; | ||
| 207 | my $f = $features->as_hash; | ||
| 208 | my @ordered_keys = (sort {$feature_indices{$a} <=> $feature_indices{$b}} | ||
| 209 | grep {exists $feature_indices{$_}} | ||
| 210 | keys %$f); | ||
| 211 | |||
| 212 | print $fh ("{", | ||
| 213 | join(', ', map("$feature_indices{$_} $f->{$_}", @ordered_keys), "$last_index '$cat'"), | ||
| 214 | "}\n" | ||
| 215 | ); | ||
| 216 | } | ||
| 217 | |||
| 218 | return $filename; | ||
| 219 | } | ||
| 220 | |||
| 221 | sub save_state { | ||
| 222 | my ($self, $path) = @_; | ||
| 223 | |||
| 224 | { | ||
| 225 | local $self->{knowledge_set}; | ||
| 226 | $self->SUPER::save_state($path); | ||
| 227 | } | ||
| 228 | return unless $self->{model}; | ||
| 229 | |||
| 230 | my $model_dir = File::Spec->catdir($path, 'models'); | ||
| 231 | mkdir($model_dir, 0777) or die "Couldn't create $model_dir: $!"; | ||
| 232 | while (my ($name, $learner) = each %{$self->{model}{learners}}) { | ||
| 233 | my $oldpath = File::Spec->catdir($self->{model}{_in_dir}, $learner->{machine_file}); | ||
| 234 | my $newpath = File::Spec->catfile($model_dir, "${name}_model"); | ||
| 235 | File::Copy::copy($oldpath, $newpath); | ||
| 236 | } | ||
| 237 | $self->{model}{_in_dir} = $model_dir; | ||
| 238 | } | ||
| 239 | |||
| 240 | sub restore_state { | ||
| 241 | my ($pkg, $path) = @_; | ||
| 242 | |||
| 243 | my $self = $pkg->SUPER::restore_state($path); | ||
| 244 | |||
| 245 | my $model_dir = File::Spec->catdir($path, 'models'); | ||
| 246 | return $self unless -e $model_dir; | ||
| 247 | $self->{model}{_in_dir} = $model_dir; | ||
| 248 | |||
| 249 | return $self; | ||
| 250 | } | ||
| 251 | |||
| 252 | 1; | ||
| 253 | |||
| 254 | __END__ |