Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added new "probabilities" method #3

Merged
merged 1 commit into from
Jul 8, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions src/Bayes.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,32 @@ public function categorize($text)
$maxProbability = -INF;
$chosenCategory = null;

if ($self->totalDocuments > 0) {
$probabilities = $self->probabilities($text);

// iterate thru our categories to find the one with max probability
// for this text
foreach ($probabilities as $category => $logProbability) {
if ($logProbability > $maxProbability) {
$maxProbability = $logProbability;
$chosenCategory = $category;
}
}
}

return $chosenCategory;
}

/**
* Extract the probabilities for each known category
* @param string $text
* @return array probabilities by category or null
*/
public function probabilities($text)
{
$self = $this;
$probabilities = [];

if ($self->totalDocuments > 0) {
$tokens = ($self->tokenizer)($text);
$frequencyTable = $self->frequencyTable($tokens);
Expand All @@ -222,15 +248,12 @@ public function categorize($text)
// determine the log of the P( w | c ) for this word
$logProbability += $frequencyInText * log($tokenProbability);
}

if ($logProbability > $maxProbability) {
$maxProbability = $logProbability;
$chosenCategory = $category;
}

$probabilities[$category] = $logProbability;
}
}

return $chosenCategory;
return $probabilities;
}

/**
Expand Down