楼主: ReneeBK
1137 2

Naive Bayes using JavaScript [推广有奖]

  • 1关注
  • 62粉丝

VIP

已卖:4900份资源

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

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

楼主
ReneeBK 发表于 2016-6-26 23:50:56 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

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

经管之家联合CDA

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

感谢您参与论坛问题回答

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

+2 论坛币
  1. Methods

  2. new NaiveBayes()

  3. Constructor that takes no arguments.

  4. Example

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

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

  8. Arguments

  9. trainingSet - A matrix of the training set.
  10. trainingLabels - An array of value for each case in the training set.
  11. Example

  12. var cases = [[6,148,72,35,0,33.6,0.627,5],
  13.              [1.50,85,66.5,29,0,26.6,0.351,31],
  14.              [8,183,64,0,0,23.3,0.672,32],
  15.              [0.5,89,65.5,23,94,28.1,0.167,21],
  16.              [0,137,40,35,168,43.1,2.288,33]];
  17. var predictions = [1, 0, 1, 0, 1];

  18. nb.train(trainingSet, predictions);
  19. predict(dataset)

  20. Predict the values of the dataset.

  21. Arguments

  22. dataset - A matrix that contains the dataset.
  23. Example

  24. var dataset = [[6,148,72,35,0,33.6,0.627,5],
  25.                [1.50,85,66.5,29,0,26.6,0.351,31]];

  26. var ans = nb.predict(dataset);
  27. export()

  28. Exports the actual Naive Bayes model to an Javascript Object.

  29. load(model)

  30. Returns a new Naive Bayes Classifier with the given model.

  31. Arguments

  32. model - Javascript Object generated from export() function.
  33. Authors

  34. Jefferson Hernandez
  35. License

  36. MIT
复制代码

本帖隐藏的内容

naive-bayes-master.zip (6.34 KB)


二维码

扫码加我 拉你入群

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

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

关键词:Javascript script naive scrip Using training matrix values

本帖被以下文库推荐

沙发
ReneeBK 发表于 2016-6-26 23:51:33
  1. 'use strict';

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

  4. module.exports.NaiveBayes = NaiveBayes;
  5. module.exports.separateClasses = separateClasses;

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

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

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

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

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

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

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

  50.     this.calculateProbabilities = calculateProbabilities;
  51. };

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

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

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

  65.     return predictions;
  66. };

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

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

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

  90.     return predictedClass;
  91. }

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

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

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

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

  125. /**
  126. * Function that retuns an array of matrices of the cases that belong to each class.
  127. * @param X - dataset
  128. * @param y - predictions
  129. * @returns {Array}
  130. */
  131. function separateClasses(X, y) {
  132.     var features = X.columns;

  133.     var classes = 0;
  134.     var totalPerClasses = new Array(100); // max upperbound of classes
  135.     for (var i = 0; i < y.length; i++) {
  136.         if(totalPerClasses[y[i]] === undefined) {
  137.             totalPerClasses[y[i]] = 0;
  138.             classes++;
  139.         }
  140.         totalPerClasses[y[i]]++;
  141.     }
  142.     var separatedClasses = new Array(classes);
  143.     var currentIndex = new Array(classes);
  144.     for(i = 0; i < classes; ++i) {
  145.         separatedClasses[i] = new Matrix(totalPerClasses[i], features);
  146.         currentIndex[i] = 0;
  147.     }
  148.     for(i = 0; i < X.rows; ++i) {
  149.         separatedClasses[y[i]].setRow(currentIndex[y[i]], X.getRow(i));
  150.         currentIndex[y[i]]++;
  151.     }
  152.     return separatedClasses;
  153. }
  154. Status API Training Shop Blog About
  155. © 2016 GitHub, Inc. Terms Privacy Security Contact
复制代码

藤椅
reflets 发表于 2016-6-27 00:42:04
did you write these codes ? looks great !

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

本版微信群
扫码
拉您进交流群
GMT+8, 2026-1-18 19:05