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

37 lines
820 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\Classification;
2016-02-09 06:45:07 +00:00
2016-05-07 21:04:58 +00:00
use Phpml\Helper\Predictable;
use Phpml\Helper\Trainable;
2016-04-16 19:24:40 +00:00
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 = [];
2016-06-16 07:58:12 +00:00
foreach ($this->targets as $index => $label) {
2016-04-14 20:56:54 +00:00
$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
}