deepbox/ml
Naive Bayes
Gaussian, multinomial, Bernoulli, complement and categorical Naive Bayes classifiers.
- Probabilistic
Overview
- Pick the estimator by feature type:
GaussianNBfor continuous features,MultinomialNBandComplementNBfor non-negative counts,BernoulliNBfor binary features, andCategoricalNBfor integer category codes. MultinomialNB,BernoulliNB,CategoricalNBandComplementNBsmooth withalpha: 1.0.GaussianNBaddsvarSmoothing: 1e-9times the largest feature variance.BernoulliNBthresholds features at 0 unless you setbinarize.- All of them have
predictProba. Fixed class priors go inpriors(GaussianNB) orclassPrior(the others), andfitPrior: falseswitches to uniform priors.
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
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 | undefinedGet the unique class labels discovered during fitting.
fit(X: Tensor, y: Tensor): thisFit Gaussian Naive Bayes classifier from the training set.
predict(X: Tensor): TensorPredict class labels for samples in X.
predictProba(X: Tensor): TensorPredict class probabilities for samples in X.
predictLogProba(X: Tensor): TensorPredict log class probabilities for samples in X.
score(X: Tensor, y: Tensor): numberReturn the mean accuracy on the given test data and labels.
getParams(): Record<string, unknown>Get hyperparameters for this estimator.
setParams(params: Record<string, unknown>): thisSet the parameters of this estimator.
clone(): GaussianNBCreate 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.
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 | undefinedSorted class labels seen during
fit, orundefinedbefore fitting.fit(X: Tensor, y: Tensor): thisFit the classifier.
predict(X: Tensor): TensorPredict class labels.
predictProba(X: Tensor): TensorPredict class probabilities.
predictLogProba(X: Tensor): TensorPredict log class probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data and labels.
getParams(): Record<string, unknown>Hyperparameters of this estimator.
setParams(params: Record<string, unknown>): thisUpdate hyperparameters.
clone(): BernoulliNBCreate 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).
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 | undefinedSorted class labels seen during
fit, orundefinedbefore fitting.nCategories: TensorNumber of categories used for smoothing in each feature, as a 1-D tensor.
fit(X: Tensor, y: Tensor): thisFit the classifier.
predict(X: Tensor): TensorPredict class labels.
predictProba(X: Tensor): TensorPredict class probabilities.
predictLogProba(X: Tensor): TensorPredict log class probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data and labels.
getParams(): Record<string, unknown>Hyperparameters of this estimator.
setParams(params: Record<string, unknown>): thisUpdate hyperparameters.
clone(): CategoricalNBCreate 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.
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 | undefinedSorted class labels seen during
fit, orundefinedbefore fitting.fit(X: Tensor, y: Tensor): thisFit the classifier on non-negative feature counts.
predict(X: Tensor): TensorPredict class labels.
predictProba(X: Tensor): TensorPredict class probabilities (softmax of the complement scores).
predictLogProba(X: Tensor): TensorPredict log class probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data and labels.
getParams(): Record<string, unknown>Hyperparameters of this estimator.
setParams(params: Record<string, unknown>): thisUpdate hyperparameters.
clone(): ComplementNBCreate 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.
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 | undefinedSorted class labels seen during
fit, orundefinedbefore fitting.fit(X: Tensor, y: Tensor): thisFit the classifier on non-negative feature counts.
predict(X: Tensor): TensorPredict class labels.
predictProba(X: Tensor): TensorPredict class probabilities.
predictLogProba(X: Tensor): TensorPredict log class probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data and labels.
getParams(): Record<string, unknown>Hyperparameters of this estimator.
setParams(params: Record<string, unknown>): thisUpdate hyperparameters.
clone(): MultinomialNBCreate an unfitted copy with the same hyperparameters.
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());Found a mistake? Open an issue.