|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace NlpTools\Classifiers; |
| 4 | + |
| 5 | +use \NlpTools\Documents\Document; |
| 6 | +use \NlpTools\FeatureFactories\FeatureFactory; |
| 7 | +use \NlpTools\Models\MultinomialNBModel; |
| 8 | + |
| 9 | +/** |
| 10 | + * Use a multinomia NB model to classify a document |
| 11 | + */ |
| 12 | +class MultinomialNBClassifier implements Classifier |
| 13 | +{ |
| 14 | + // The feature factory |
| 15 | + protected $feature_factory; |
| 16 | + // The NBModel |
| 17 | + protected $model; |
| 18 | + |
| 19 | + public function __construct(FeatureFactory $ff, MultinomialNBModel $m) { |
| 20 | + $this->feature_factory = $ff; |
| 21 | + $this->model = $m; |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Compute the probability of $d belonging to each class |
| 26 | + * successively and return that class that has the maximum |
| 27 | + * probability. |
| 28 | + * |
| 29 | + * @param array $classes The classes from which to choose |
| 30 | + * @param Document $d The document to classify |
| 31 | + * @return string $class The class that has the maximum probability |
| 32 | + */ |
| 33 | + public function classify(array $classes, Document $d) { |
| 34 | + $maxclass = current($classes); |
| 35 | + $maxscore = $this->getScore($maxclass,$d); |
| 36 | + while ($class=next($classes)) |
| 37 | + { |
| 38 | + $score = $this->getScore($class,$d); |
| 39 | + if ($score>$maxscore) |
| 40 | + { |
| 41 | + $maxclass = $class; |
| 42 | + $maxscore = $score; |
| 43 | + } |
| 44 | + } |
| 45 | + return $maxclass; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Compute the log of the probability of the Document $d belonging |
| 50 | + * to class $class. We compute the log so that we can sum over the |
| 51 | + * logarithms instead of multiplying each probability. |
| 52 | + * |
| 53 | + * @todo perhaps MultinomialNBModel should have precomputed the logs |
| 54 | + * ex.: getLogPrior() and getLogCondProb() |
| 55 | + * |
| 56 | + * @param string $class The class for which we are getting a score |
| 57 | + * @param Document The document whose score we are getting |
| 58 | + * @return float The log of the probability of $d belonging to $class |
| 59 | + */ |
| 60 | + public function getScore($class, Document $d) { |
| 61 | + $score = log($this->model->getPrior($class)); |
| 62 | + $features = $this->feature_factory->getFeatureArray($class,$d); |
| 63 | + if (is_int(key($features))) |
| 64 | + $features = array_count_values($features); |
| 65 | + foreach ($features as $f=>$fcnt) |
| 66 | + { |
| 67 | + $score += $fcnt*log($this->model->getCondProb($f,$class)); |
| 68 | + } |
| 69 | + return $score; |
| 70 | + } |
| 71 | + |
| 72 | +} |
| 73 | + |
| 74 | +?> |
0 commit comments