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

New method: .probabilities() #7

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
37 changes: 29 additions & 8 deletions lib/naive_bayes.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,13 +177,36 @@ Naivebayes.prototype.categorize = function (text) {
, maxProbability = -Infinity
, chosenCategory = null

var probabilities = self.probabilities(text)

//iterate thru our categories to find the one with max probability for this text
probabilities
.forEach(function (categoryProbability) {
if (categoryProbability.value > maxProbability) {
maxProbability = categoryProbability.value
chosenCategory = categoryProbability.category
}
})

return chosenCategory;
}

/**
* Determine category probabilities for `text`.
*
* @param {String} text
* @return {Array} probabilities
*/
Naivebayes.prototype.probabilities = function(text) {
var self = this;

var tokens = self.tokenizer(text)
var frequencyTable = self.frequencyTable(tokens)

//iterate thru our categories to find the one with max probability for this text
Object
//iterate thru our categories to calculate the probability for this text
return Object
.keys(self.categories)
.forEach(function (category) {
.map(function (category) {

//start by calculating the overall probability of this category
//=> out of all documents we've ever looked at, how many were
Expand All @@ -206,13 +229,11 @@ Naivebayes.prototype.categorize = function (text) {
logProbability += frequencyInText * Math.log(tokenProbability)
})

if (logProbability > maxProbability) {
maxProbability = logProbability
chosenCategory = category
return {
category: category,
value: logProbability
}
})

return chosenCategory
}

/**
Expand Down
4 changes: 4 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ Teach your classifier what `category` the `text` belongs to. The more you teach

Returns the `category` it thinks `text` belongs to. Its judgement is based on what you have taught it with **.learn()**.

###`classifier.probabilities(text)`

Returns an array of `{ value, category }` objects with probability calculated for each category. Its judgement is based on what you have taught it with **.learn()**.

###`classifier.toJson()`

Returns the JSON representation of a classifier.
Expand Down