AI-DecisionTree
view release on metacpan or search on metacpan
t/02-noisy.t view on Meta::CPAN
# Before `make install' is performed this script should be runnable with
# `make test'. After `make install' it should work as `perl test.pl'
#########################
use Test;
BEGIN { plan tests => 5 };
use AI::DecisionTree;
ok(1); # If we made it this far, we're ok.
#########################
my $dtree = AI::DecisionTree->new(noise_mode => 'pick_best');
ok $dtree;
my @names = split /, /, <DATA>;
chomp $names[-1];
# Train on first 600 instances
printf "Loading 600 training instances with %d attribute types each\n", scalar @names;
while (<DATA>) {
last unless 2..601;
chomp;
my @values = split /, /, $_;
my $result = pop @values;
my %pairs = map {$names[$_], $values[$_]} 0..$#names;
$dtree->add_instance(attributes => \%pairs,
result => $result,
);
}
print "Building decision tree\n";
$dtree->train;
ok(1);
# Test on rest of data, get at least 80%
print "Testing on remainder of data\n";
my ($good, $bad) = (0,0);
while (<DATA>) {
chomp;
my @values = split /, /, $_;
my $result = pop @values;
my %pairs = map {$names[$_], $values[$_]} 0..$#names;
my ($guess, $confidence) = $dtree->get_result(attributes => \%pairs);
$guess ||= ''; $confidence ||= '';
($guess eq $result ? $good : $bad)++;
#print "$guess : $result : $confidence\n";
}
my $accuracy = $good/($good + $bad);
ok $accuracy > .8;
print "Accuracy=$accuracy\n";
#use YAML; print Dump($dtree->rule_tree);
#print map "$_\n", $dtree->rule_statements;
if (eval "use GraphViz; 1") {
my $graphviz = $dtree->as_graphviz;
ok $graphviz;
if (0) {
# Only works on Mac OS X
my $file = '/tmp/tree2.png';
open my($fh), "> $file" or die "$file: $!";
print $fh $graphviz->as_png;
( run in 1.647 second using v1.01-cache-2.11-cpan-39bf76dae61 )