Bayes
by bkanber
HTML
<textarea id="test_phrase" placeholder="Enter English, Spanish, or French text here."></textarea>
<button id="test_button" onclick="go();">Guess Language</button>
<h2 id="test_result"></h2>
<p id="test_probability"></p>
CSS
body, textarea, button {
font-family:Helvetica, Arial, sans-serif;
}
textarea {
width:300px;
height:100px;
resize:none;
display:block;
padding:10px;
margin:10px auto;
}
button {
display:block;
margin:auto;
}
h2, p {
text-align:center;
}
JavaScript
/*
The following is not free software. You may use it for educational purposes, but you may not redistribute or use it commercially.
(C) All Rights Reserved, Burak Kanber 2013
*/
var Bayes = (function (Bayes) {
Array.prototype.unique = function () {
var u = {}, a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
var stemKey = function (stem, label) {
return '_Bayes::stem:' + stem + '::label:' + label;
};
var docCountKey = function (label) {
return '_Bayes::docCount:' + label;
};
var stemCountKey = function (stem) {
return '_Bayes::stemCount:' + stem;
};
var log = function (text) {
console.log(text);
};
var tokenize = function (text) {
text = text.toLowerCase().replace(/\W/g, ' ').replace(/\s+/g, ' ').trim().split(' ').unique();
return text;
};
var getLabels = function () {
var labels = localStorage.getItem('_Bayes::registeredLabels');
if (!labels) labels = '';
return labels.split(',').filter(function (a) {
return a.length;
});
};
var registerLabel = function (label) {
var labels = getLabels();
if (labels.indexOf(label) === -1) {
labels.push(label);
localStorage.setItem('_Bayes::registeredLabels', labels.join(','));
}
return true;
};
var stemLabelCount = function (stem, label) {
var count = parseInt(localStorage.getItem(stemKey(stem, label)));
if (!count) count = 0;
return count;
};
var stemInverseLabelCount = function (stem, label) {
var labels = getLabels();
var total = 0;
for (var i = 0, length = labels.length; i < length; i++) {
if (labels[i] === label)
continue;
...