这是我编写的一些代码,用于使用朴素贝叶斯分类器计算关于某些观察到的特征的标签概率。这旨在计算朴素贝叶斯公式而不进行平滑处理,并且旨在计算实际概率,因此请使用通常省略的分母。我遇到的问题是,对于示例(如下),“好”标签的概率> 1。(1.30612245)谁能帮我理解那是什么?这是天真的假设的副产品吗?
package NaiveBayes;
use Moose;
has class_counts => (is => 'ro', isa => 'HashRef[Int]', default => sub {{}});
has class_feature_counts => (is => 'ro', isa => 'HashRef[HashRef[HashRef[Num]]]', default => sub {{}});
has feature_counts => (is => 'ro', isa => 'HashRef[HashRef[Num]]', default => sub {{}});
has total_observations => (is => 'rw', isa => 'Num');
sub insert {
my( $self, $class, $data ) = @_;
$self->class_counts->{$class}++;
$self->total_observations( ($self->total_observations||0) + 1 );
for( keys %$data ){
$self->feature_counts->{$_}->{$data->{$_}}++;
$self->class_feature_counts->{$_}->{$class}->{$data->{$_}}++;
}
return $self;
}
sub classify {
my( $self, $data ) = @_;
my %probabilities;
my $feature_probability = 1;
for my $class( keys %{ $self->class_counts } ) {
my $class_count = $self->class_counts->{$class};
my $class_probability = $class_count / $self->total_observations;
my($feature_probability, $conditional_probability) = (1) x 2;
my( @feature_probabilities, @conditional_probabilities );
for( keys %$data ){
my $feature_count = $self->feature_counts->{$_}->{$data->{$_}};
my $class_feature_count = $self->class_feature_counts->{$_}->{$class}->{$data->{$_}} || 0;
next unless $feature_count;
$feature_probability *= $feature_count / $self->total_observations;
$conditional_probability *= $class_feature_count / $class_count;
}
$probabilities{$class} = $class_probability * $conditional_probability / $feature_probability;
}
return %probabilities;
}
__PACKAGE__->meta->make_immutable;
1;
例子:
#!/usr/bin/env perl
use Moose;
use NaiveBayes;
my $nb = NaiveBayes->new;
$nb->insert('good' , {browser => 'chrome' ,host => 'yahoo' ,country => 'us'});
$nb->insert('bad' , {browser => 'chrome' ,host => 'slashdot' ,country => 'us'});
$nb->insert('good' , {browser => 'chrome' ,host => 'slashdot' ,country => 'uk'});
$nb->insert('good' , {browser => 'explorer' ,host => 'google' ,country => 'us'});
$nb->insert('good' , {browser => 'explorer' ,host => 'slashdot' ,country => 'ca'});
$nb->insert('good' , {browser => 'opera' ,host => 'google' ,country => 'ca'});
$nb->insert('good' , {browser => 'firefox' ,host => '4chan' ,country => 'us'});
$nb->insert('good' , {browser => 'opera' ,host => '4chan' ,country => 'ca'});
my %classes = $nb->classify({browser => 'opera', host => '4chan', country =>'uk'});
my @classes = sort { $classes{$a} <=> $classes{$b} } keys %classes;
for( @classes ){
printf( "%-20s : %5.8f\n", $_, $classes{$_} );
}
印刷:
bad : 0.00000000
good : 1.30612245
我不太担心 0 的概率,但更担心好的 > 1 的“概率”。我相信这是经典朴素贝叶斯定义的实现。
p(C│F_1 ...F_n )=(p(C)p(F_1 |C)...p(F_n |C))/(p(F_1)...p(F_n))
这怎么可能> 1?