Skip to content

Instantly share code, notes, and snippets.

@3den
Created October 26, 2013 09:19
Show Gist options
  • Select an option

  • Save 3den/7167223 to your computer and use it in GitHub Desktop.

Select an option

Save 3den/7167223 to your computer and use it in GitHub Desktop.
bayes network
var Bayes = (function(){
function constructor(positives, negatives) {
this.positives = positives;
this.negatives = negatives || reverse(positives);
}
function compute(probabilities) {
return probabilities.reduce(function(previous, current){
return previous * current;
}, 1);
}
function reverse(probabilities) {
return probabilities.map(function(value){
return 1 - value;
});
}
constructor.calculate = function(positives, negatives){
return new this(positives, negatives).calculate();
};
constructor.prototype.calculate = function(){
var p = compute(this.positives)
, r = compute(this.negatives);
return p / (p + r);
};
return constructor;
}());
if (typeof(module) !== "undefined") { module.exports = Bayes; }
var assert = require("assert")
, Bayes = require("./bayes");
describe("Bayes", function(){
it("calculates the independent probabilities", function(){
assert_calc([0.6, 0.72], undefined, 0.794118);
assert_calc([0.01, 0.9, 0.9, 0.2], undefined, 0.169811);
});
it("calculates the dependent probabilitiess", function(){
assert_calc([0.01, 0.9, 0.9], [0.99, 0.2, 0.2], 0.169811);
assert_calc([0.01, 0.9, 0.1], [0.99, 0.2, 0.8], 0.00564972);
});
function assert_calc(positives, negatives, expectation){
assert.equal(
Bayes.calculate(positives, negatives).toFixed(5),
expectation.toFixed(5)
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment