php-ml/src/Phpml/Classifier/NaiveBayes.php

37 lines
837 B
PHP
Raw Normal View History

2016-02-09 06:45:07 +00:00
<?php
2016-04-04 20:49:54 +00:00
declare (strict_types = 1);
2016-02-09 06:45:07 +00:00
namespace Phpml\Classifier;
2016-04-16 19:24:40 +00:00
use Phpml\Classifier\Traits\Predictable;
use Phpml\Classifier\Traits\Trainable;
2016-04-04 20:25:27 +00:00
class NaiveBayes implements Classifier
2016-02-09 06:45:07 +00:00
{
2016-04-16 19:24:40 +00:00
use Trainable, Predictable;
2016-04-14 20:56:54 +00:00
/**
* @param array $sample
*
* @return mixed
*/
protected function predictSample(array $sample)
2016-04-14 20:56:54 +00:00
{
$predictions = [];
foreach ($this->labels as $index => $label) {
$predictions[$label] = 0;
foreach ($sample as $token => $count) {
if (array_key_exists($token, $this->samples[$index])) {
$predictions[$label] += $count * $this->samples[$index][$token];
}
}
}
arsort($predictions, SORT_NUMERIC);
reset($predictions);
return key($predictions);
2016-04-04 20:25:27 +00:00
}
2016-02-09 06:45:07 +00:00
}