楼主: ReneeBK
1345 3

【JavaScript】Naive Bayes [推广有奖]

  • 1关注
  • 62粉丝

VIP

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49407 个
通用积分
51.8704
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57815 点
帖子
4006
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

相似文件 换一批

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
Naive Bayes

Naive bayes classifier.

Methodsnew NaiveBayes()

Constructor that takes no arguments.

Example

var nb = new NaiveBayes();
train(trainingSet, predictions)

Train the Naive Bayes model to the given training set and predictions

Arguments

  • trainingSet - A matrix of the training set.
  • trainingLabels - An array of value for each case in the training set.

本帖隐藏的内容

naive-bayes-master.zip (8.01 KB)

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Javascript script naive Bayes scrip training matrix

本帖被以下文库推荐

沙发
ReneeBK 发表于 2017-4-16 04:09:12 |只看作者 |坛友微信交流群
  1. "use strict";

  2. var Matrix = require('ml-matrix');
  3. var Utils = require('./utils');

  4. class MultinomialNB {
  5.     constructor(model) {
  6.     }

  7.     train(trainingSet, trainingLabels) {
  8.         trainingSet = Matrix.checkMatrix(trainingSet);
  9.         var separateClasses = Utils.separateClasses(trainingSet, trainingLabels);
  10.         this.priorProbability = new Matrix(separateClasses.length, 1);

  11.         for(var i = 0; i < separateClasses.length; ++i) {
  12.             this.priorProbability[i][0] = Math.log(separateClasses[i].length / trainingSet.rows);
  13.         }

  14.         var features = trainingSet.columns;
  15.         this.conditionalProbability = new Matrix(separateClasses.length, features);
  16.         for(i = 0; i < separateClasses.length; ++i) {
  17.             var classValues = Matrix.checkMatrix(separateClasses[i]);
  18.             var total = classValues.sum();
  19.             var divisor = total + features;
  20.             this.conditionalProbability.setRow(i, classValues.sum('column').add(1).div(divisor).apply(matrixLog));
  21.         }
  22.     }

  23.     predict(dataset) {
  24.         dataset = Matrix.checkMatrix(dataset);
  25.         var predictions = new Array(dataset.rows);
  26.         for(var i = 0; i < dataset.rows; ++i) {
  27.             var currentElement = dataset.getRowVector(i);
  28.             predictions[i] = this.conditionalProbability.clone().mulRowVector(currentElement).sum('row')
  29.                              .add(this.priorProbability).maxIndex()[0];
  30.         }
  31.     }

  32.     toJSON() {

  33.     }

  34.     load() {

  35.     }
  36. }

  37. function matrixLog(i, j) {
  38.     this[i][j] = Math.log(this[i][j]);
  39. }

  40. module.exports = MultinomialNB;
复制代码

使用道具

藤椅
ReneeBK 发表于 2017-4-16 04:09:40 |只看作者 |坛友微信交流群
  1. 'use strict';

  2. var Matrix = require('ml-matrix');
  3. var Stat = require('ml-stat');
  4. var Utils = require('./utils');

  5. module.exports = NaiveBayes;
  6. //module.exports.separateClasses = separateClasses;

  7. /**
  8. * Constructor for the Naive Bayes classifier, the parameters here is just for loading purposes.
  9. *
  10. * @param reload
  11. * @param model
  12. * @constructor
  13. */
  14. function NaiveBayes(reload, model) {
  15.     if(reload) {
  16.         this.means = model.means;
  17.         this.calculateProbabilities = model.calculateProbabilities;
  18.     }
  19. }

  20. /**
  21. * Function that trains the classifier with a matrix that represents the training set and an array that
  22. * represents the label of each row in the training set. the labels must be numbers between 0 to n-1 where
  23. * n represents the number of classes.
  24. *
  25. * WARNING: in the case that one class, all the cases in one or more features have the same value, the
  26. * Naive Bayes classifier will not work well.
  27. * @param trainingSet
  28. * @param trainingLabels
  29. */
  30. NaiveBayes.prototype.train = function (trainingSet, trainingLabels) {
  31.     var C1 = Math.sqrt(2*Math.PI); // constant to precalculate the squared root
  32.     if(!Matrix.isMatrix(trainingSet)) trainingSet = new Matrix(trainingSet);
  33.     else trainingSet = trainingSet.clone();

  34.     if(trainingSet.rows !== trainingLabels.length)
  35.         throw new RangeError("the size of the training set and the training labels must be the same.");

  36.     var separatedClasses = Utils.separateClasses(trainingSet, trainingLabels);
  37.     var calculateProbabilities = new Array(separatedClasses.length);
  38.     this.means = new Array(separatedClasses.length);
  39.     for(var i = 0; i < separatedClasses.length; ++i) {
  40.         var means = Stat.matrix.mean(separatedClasses[i]);
  41.         var std = Stat.matrix.standardDeviation(separatedClasses[i], means);

  42.         var logPriorProbability = Math.log(separatedClasses[i].rows / trainingSet.rows);
  43.         calculateProbabilities[i] = new Array(means.length + 1);

  44.         calculateProbabilities[i][0] = logPriorProbability;
  45.         for(var j = 1; j < means.length + 1; ++j) {
  46.             var currentStd = std[j - 1];
  47.             calculateProbabilities[i][j] = [(1 / (C1 * currentStd)), -2*currentStd*currentStd];
  48.         }

  49.         this.means[i] = means;
  50.     }

  51.     this.calculateProbabilities = calculateProbabilities;
  52. };

  53. /**
  54. * function that predicts each row of the dataset (must be a matrix).
  55. *
  56. * @param dataset
  57. * @returns {Array}
  58. */
  59. NaiveBayes.prototype.predict = function (dataset) {
  60.     if(dataset[0].length === this.calculateProbabilities[0].length)
  61.         throw new RangeError('the dataset must have the same features as the training set');

  62.     var predictions = new Array(dataset.length);

  63.     for(var i = 0; i < predictions.length; ++i) {
  64.         predictions[i] = getCurrentClass(dataset[i], this.means, this.calculateProbabilities);
  65.     }

  66.     return predictions;
  67. };

  68. /**
  69. * Function the retrieves a prediction with one case.
  70. *
  71. * @param currentCase
  72. * @param mean - Precalculated means of each class trained
  73. * @param classes - Precalculated value of each class (Prior probability and probability function of each feature)
  74. * @returns {number}
  75. */
  76. function getCurrentClass(currentCase, mean, classes) {
  77.     var maxProbability = 0;
  78.     var predictedClass = -1;

  79.     // going through all precalculated values for the classes
  80.     for(var i = 0; i < classes.length; ++i) {
  81.         var currentProbability = classes[i][0]; // initialize with the prior probability
  82.         for(var j = 1; j < mean[0].length + 1; ++j) {
  83.             currentProbability += calculateLogProbability(currentCase[j - 1], mean[i][j - 1], classes[i][j][0], classes[i][j][1]);
  84.         }

  85.         currentProbability = Math.exp(currentProbability);
  86.         if(currentProbability > maxProbability) {
  87.             maxProbability = currentProbability;
  88.             predictedClass = i;
  89.         }
  90.     }

  91.     return predictedClass;
  92. }

  93. /**
  94. * Function that export the NaiveBayes model.
  95. * @returns {{modelName: string, means: *, calculateProbabilities: *}}
  96. */
  97. NaiveBayes.prototype.export = function () {
  98.     return {
  99.         modelName: "NaiveBayes",
  100.         means: this.means,
  101.         calculateProbabilities: this.calculateProbabilities
  102.     };
  103. };

  104. /**
  105. * Function that create a Naive Bayes classifier with the given model.
  106. * @param model
  107. * @returns {NaiveBayes}
  108. */
  109. NaiveBayes.load = function (model) {
  110.     if(model.modelName !== 'NaiveBayes')
  111.         throw new RangeError("The given model is invalid!");

  112.     return new NaiveBayes(true, model);
  113. };

  114. /**
  115. * function that retrieves the probability of the feature given the class.
  116. * @param value - value of the feature.
  117. * @param mean - mean of the feature for the given class.
  118. * @param C1 - precalculated value of (1 / (sqrt(2*pi) * std)).
  119. * @param C2 - precalculated value of (2 * std^2) for the denominator of the exponential.
  120. * @returns {number}
  121. */
  122. function calculateLogProbability(value, mean, C1, C2) {
  123.     var value = value - mean;
  124.     return Math.log(C1 * Math.exp((value * value) / C2))
  125. }
复制代码

使用道具

板凳
WFMZZ 发表于 2017-4-19 09:58:40 |只看作者 |坛友微信交流群

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-26 19:53