Skip to content

deepbox/ml

Naive Bayes

Gaussian, multinomial, Bernoulli, complement and categorical Naive Bayes classifiers.

  • Probabilistic

Overview

  • Pick the estimator by feature type: GaussianNB for continuous features, MultinomialNB and ComplementNB for non-negative counts, BernoulliNB for binary features, and CategoricalNB for integer category codes.
  • MultinomialNB, BernoulliNB, CategoricalNB and ComplementNB smooth with alpha: 1.0. GaussianNB adds varSmoothing: 1e-9 times the largest feature variance. BernoulliNB thresholds features at 0 unless you set binarize.
  • All of them have predictProba. Fixed class priors go in priors (GaussianNB) or classPrior (the others), and fitPrior: false switches to uniform priors.

Classes

5

GaussianNB

Gaussian Naive Bayes classifier.

Implements the Gaussian Naive Bayes algorithm for classification. Assumes features follow a Gaussian (normal) distribution.

Algorithm: 1. Calculate mean and variance for each feature per class 2. For prediction, calculate likelihood using Gaussian PDF 3. Apply Bayes' theorem to get posterior probabilities 4. Predict class with highest posterior probability

Like scikit-learn, varSmoothing is a fraction of the largest per-feature variance of the whole training set; that value is added to every class variance. If every feature is constant, varSmoothing itself is added.

Time Complexity: - Training: O(n * d) where n=samples, d=features - Prediction: O(k * d) per sample where k=classes

Example
import { GaussianNB } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 2], [2, 3], [3, 4], [4, 5]]);const y = tensor([0, 0, 1, 1]); const nb = new GaussianNB();nb.fit(X, y); const predictions = nb.predict(tensor([[2.5, 3.5]]));
Members (10)
  • constructor(options?: { readonly varSmoothing?: number; readonly priors?: readonly number[] | null; })

    Create a new Gaussian Naive Bayes classifier.

  • classes: Tensor | undefined

    Get the unique class labels discovered during fitting.

  • fit(X: Tensor, y: Tensor): this

    Fit Gaussian Naive Bayes classifier from the training set.

  • predict(X: Tensor): Tensor

    Predict class labels for samples in X.

  • predictProba(X: Tensor): Tensor

    Predict class probabilities for samples in X.

  • predictLogProba(X: Tensor): Tensor

    Predict log class probabilities for samples in X.

  • score(X: Tensor, y: Tensor): number

    Return the mean accuracy on the given test data and labels.

  • getParams(): Record<string, unknown>

    Get hyperparameters for this estimator.

  • setParams(params: Record<string, unknown>): this

    Set the parameters of this estimator.

  • clone(): GaussianNB

    Create an unfitted copy with the same hyperparameters.

BernoulliNB

Bernoulli Naive Bayes classifier.

Like MultinomialNB, this classifier is suitable for discrete data. The difference is that while MultinomialNB works with occurrence counts, BernoulliNB is designed for binary/boolean features. A feature counts as present when its value is strictly greater than the binarize threshold. With binarize: null the threshold is 0, so 0/1 data is used as is. Absent features contribute log(1 - p) to the score, which distinguishes this model from MultinomialNB.

Example
import { BernoulliNB } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 0, 1], [0, 1, 1], [1, 0, 0], [0, 1, 0]]);const y = tensor([0, 1, 0, 1]); const clf = new BernoulliNB();clf.fit(X, y);const predictions = clf.predict(tensor([[1, 0, 1]]));
Members (10)
  • constructor(options?: { readonly alpha?: number; readonly binarize?: number | null; readonly fitPrior?: boolean; readonly classPrior?: readonly number[] | null; })
  • classes: Tensor | undefined

    Sorted class labels seen during fit, or undefined before fitting.

  • fit(X: Tensor, y: Tensor): this

    Fit the classifier.

  • predict(X: Tensor): Tensor

    Predict class labels.

  • predictProba(X: Tensor): Tensor

    Predict class probabilities.

  • predictLogProba(X: Tensor): Tensor

    Predict log class probabilities.

  • score(X: Tensor, y: Tensor): number

    Mean accuracy on the given data and labels.

  • getParams(): Record<string, unknown>

    Hyperparameters of this estimator.

  • setParams(params: Record<string, unknown>): this

    Update hyperparameters.

  • clone(): BernoulliNB

    Create an unfitted copy with the same hyperparameters.

CategoricalNB

Categorical Naive Bayes classifier.

Suitable for classification with discrete/categorical features. Each feature is assumed to be generated from a categorical distribution.

Unlike MultinomialNB (which models feature counts) or BernoulliNB (binary), CategoricalNB models each feature as having its own set of categories.

Algorithm: 1. For each feature and each class, compute the probability of each category using smoothed maximum likelihood estimates. 2. For prediction, compute the log posterior for each class.

Categories: a feature's categories are the distinct values seen in training. When every training value of a feature is a non-negative integer (ordinal codes, as scikit-learn requires), the categories are 0..max, so codes that never appear still count towards the smoothing denominator; minCategories raises that count further. A category not seen for a class, or not seen at all, gets probability alpha / (count_c + alpha * n_categories).

Example
import { CategoricalNB } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; // Categorical features (e.g., color=0/1/2, size=0/1)const X = tensor([[0, 0], [1, 1], [2, 0], [0, 1], [1, 0], [2, 1]]);const y = tensor([0, 0, 0, 1, 1, 1]); const clf = new CategoricalNB();clf.fit(X, y);const predictions = clf.predict(tensor([[1, 0]]));
Members (11)
  • constructor(options?: { readonly alpha?: number; readonly fitPrior?: boolean; readonly classPrior?: readonly number[] | null; readonly minCategories?: number | readonly number[] | null; })
  • classes: Tensor | undefined

    Sorted class labels seen during fit, or undefined before fitting.

  • nCategories: Tensor

    Number of categories used for smoothing in each feature, as a 1-D tensor.

  • fit(X: Tensor, y: Tensor): this

    Fit the classifier.

  • predict(X: Tensor): Tensor

    Predict class labels.

  • predictProba(X: Tensor): Tensor

    Predict class probabilities.

  • predictLogProba(X: Tensor): Tensor

    Predict log class probabilities.

  • score(X: Tensor, y: Tensor): number

    Mean accuracy on the given data and labels.

  • getParams(): Record<string, unknown>

    Hyperparameters of this estimator.

  • setParams(params: Record<string, unknown>): this

    Update hyperparameters.

  • clone(): CategoricalNB

    Create an unfitted copy with the same hyperparameters.

ComplementNB

Complement Naive Bayes classifier.

An adaptation of the standard Multinomial Naive Bayes that is particularly suited for imbalanced datasets. Instead of computing the likelihood from samples of a class, it uses the complement (all samples NOT in the class).

Algorithm (as in scikit-learn): 1. For each class c, count every feature over the samples of all other classes and smooth the counts with alpha. 2. Take w_cj = -log(theta_cj), where theta_cj is the smoothed complement frequency of feature j. With norm: true the weights of each class are divided by their sum (the L1 norm, since all weights are positive). 3. Score class c as sum_j x_j * w_cj and predict the class with the highest score.

The class prior is only used when there is a single class, as in scikit-learn.

Reference: Rennie et al., "Tackling the Poor Assumptions of Naive Bayes Text Classifiers", ICML 2003.

Example
import { ComplementNB } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[3, 0, 1], [0, 2, 1], [1, 0, 3], [0, 3, 0]]);const y = tensor([0, 1, 0, 1]); const clf = new ComplementNB();clf.fit(X, y);const predictions = clf.predict(tensor([[2, 0, 1]]));
Members (10)
  • constructor(options?: { readonly alpha?: number; readonly fitPrior?: boolean; readonly norm?: boolean; readonly classPrior?: readonly number[] | null; })
  • classes: Tensor | undefined

    Sorted class labels seen during fit, or undefined before fitting.

  • fit(X: Tensor, y: Tensor): this

    Fit the classifier on non-negative feature counts.

  • predict(X: Tensor): Tensor

    Predict class labels.

  • predictProba(X: Tensor): Tensor

    Predict class probabilities (softmax of the complement scores).

  • predictLogProba(X: Tensor): Tensor

    Predict log class probabilities.

  • score(X: Tensor, y: Tensor): number

    Mean accuracy on the given data and labels.

  • getParams(): Record<string, unknown>

    Hyperparameters of this estimator.

  • setParams(params: Record<string, unknown>): this

    Update hyperparameters.

  • clone(): ComplementNB

    Create an unfitted copy with the same hyperparameters.

MultinomialNB

Multinomial Naive Bayes classifier.

Suitable for classification with discrete features (e.g., word counts for text classification). The multinomial distribution normally requires integer feature counts, but fractional counts (e.g., TF-IDF) work in practice.

Algorithm: 1. For each class, compute the log probability of each feature using smoothed maximum likelihood estimates. 2. For prediction, compute the log posterior for each class and select the class with the highest posterior.

Example
import { MultinomialNB } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; // Word count features for text classificationconst X = tensor([[3, 0, 1], [0, 2, 1], [1, 0, 3], [0, 3, 0]]);const y = tensor([0, 1, 0, 1]); const clf = new MultinomialNB();clf.fit(X, y);const predictions = clf.predict(tensor([[2, 0, 1]]));
Members (10)
  • constructor(options?: { readonly alpha?: number; readonly fitPrior?: boolean; readonly classPrior?: readonly number[] | null; })
  • classes: Tensor | undefined

    Sorted class labels seen during fit, or undefined before fitting.

  • fit(X: Tensor, y: Tensor): this

    Fit the classifier on non-negative feature counts.

  • predict(X: Tensor): Tensor

    Predict class labels.

  • predictProba(X: Tensor): Tensor

    Predict class probabilities.

  • predictLogProba(X: Tensor): Tensor

    Predict log class probabilities.

  • score(X: Tensor, y: Tensor): number

    Mean accuracy on the given data and labels.

  • getParams(): Record<string, unknown>

    Hyperparameters of this estimator.

  • setParams(params: Record<string, unknown>): this

    Update hyperparameters.

  • clone(): MultinomialNB

    Create an unfitted copy with the same hyperparameters.

ml-naive-bayes.ts
import {  BernoulliNB,  CategoricalNB,  GaussianNB,  MultinomialNB,} from "deepbox/ml";import { tensor } from "deepbox/ndarray"; const gaussian = new GaussianNB().fit(tensor([[1], [2], [3], [4]]), tensor([0, 0, 1, 1]));console.log(gaussian.predict(tensor([[2.5]])).toString());console.log(gaussian.predictProba(tensor([[2.5]])).toString()); const binary = tensor([[0, 1], [1, 0], [1, 1]]);console.log(new BernoulliNB().fit(binary, tensor([0, 1, 1])).predict(tensor([[1, 0]])).toString()); const counts = tensor([[2, 1], [0, 3], [1, 2]]);console.log(new MultinomialNB().fit(counts, tensor([0, 1, 1])).predict(tensor([[1, 1]])).toString());console.log(new CategoricalNB().fit(binary, tensor([0, 1, 1])).predict(tensor([[1, 1]])).toString());