Skip to content

deepbox/ml

Calibration, GP & Anomaly Detection

Probability calibration, Gaussian processes, MLP estimators, semi-supervised learning, discriminant analysis and outlier detection.

  • Specialized estimators

Overview

  • CalibratedClassifierCV({ estimator, method }) fits the base estimator in place and calibrates it with Platt scaling ("sigmoid", the default) or isotonic regression on out-of-fold probabilities (cv: 5). The base estimator needs predictProba and must be rebuildable from getParams().
  • MLPClassifier and MLPRegressor are feed-forward networks trained with one-sample SGD updates. They are separate from deepbox/nn: they do not use autograd or devices. Standardize the inputs and pass randomState.
  • IsolationForest and LocalOutlierFactor default to contamination: "auto". predict returns 1 for inliers and -1 for outliers.
  • The semi-supervised estimators (LabelPropagation, LabelSpreading, SelfTrainingClassifier) read -1 in y as an unlabeled sample.
  • GaussianProcessRegressor and GaussianProcessClassifier factor an n by n kernel matrix, so cost grows as O(n^3) in the number of training samples.

Types

3

GaussianProcessClassifierOptions

type

Options for GaussianProcessClassifier.

  • readonly alpha?: number

    Value added to the diagonal of the training kernel matrix (default: 1e-5).

  • readonly lengthScale?: number

    RBF kernel length scale (default: 1.0).

  • readonly kernelVariance?: number

    RBF kernel variance (default: 1.0).

  • readonly maxLaplaceIter?: number

    Maximum Newton iterations of the Laplace approximation, per binary problem (default: 100).

GaussianProcessRegressorOptions

type

Options for GaussianProcessRegressor.

  • readonly alpha?: number

    Value added to the diagonal of the kernel matrix, i.e.

  • readonly lengthScale?: number

    RBF kernel length scale (default: 1.0).

  • readonly kernelVariance?: number

    RBF kernel variance, the prior variance of the function (default: 1.0).

  • readonly normalizeY?: boolean

    Subtract the training mean and divide by the training standard deviation before fitting, and undo this in the predictions (default: false).

SelfTrainingTermination

type

Why SelfTrainingClassifier stopped adding labels.

type SelfTrainingTermination = "max_iter" | "no_change" | "all_labeled";

Classes

12

IsolationForest

Isolation Forest for anomaly/outlier detection.

Isolates observations by randomly selecting a feature and then randomly selecting a split value between the max and min of the selected feature. Anomalies require fewer splits to be isolated, resulting in shorter path lengths.

Follows scikit-learn's IsolationForest: every tree is grown on a subsample drawn without replacement, trees are limited to depth ceil(log2(maxSamples)), constant features are skipped when choosing a split, and scoreSamples returns the negated anomaly score -2^(-E[h(x)] / c(maxSamples)) (the lower, the more abnormal). With contamination: "auto" a sample is an outlier when its anomaly score is above 0.5; otherwise the threshold is the contamination percentile of the training scores.

Example
import { IsolationForest } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0, 0], [0.1, -0.1], [0.2, 0.1], [100, 100]]);const ifo = new IsolationForest({ nEstimators: 100, contamination: 0.25, randomState: 0 });ifo.fit(X);const labels = ifo.predict(X); // -1 for outliers, 1 for inliers
Members (10)
  • constructor(options?: { readonly nEstimators?: number; readonly maxSamples?: number | "auto"; readonly contamination?: number | "auto"; readonly maxFeatures?: number; readonly randomState?: number; })
  • offset: number

    Decision threshold in scoreSamples units: samples scoring below it are outliers.

  • fit(X: Tensor, _y?: Tensor): this

    Fit the forest.

  • decisionFunction(X: Tensor): Tensor

    Opposite of the anomaly score, shifted so that negative values are outliers.

  • predict(X: Tensor): Tensor

    Predict whether each sample is an outlier.

  • fitPredict(X: Tensor, _y?: Tensor): Tensor
  • scoreSamples(X: Tensor): Tensor

    Anomaly score of each sample (lower is more abnormal).

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

    Set parameters.

  • clone(): IsolationForest

    Create an unfitted copy with the same parameters.

LocalOutlierFactor

Local Outlier Factor (LOF) for anomaly detection.

Measures the local density deviation of a data point with respect to its neighbors. Points that have substantially lower density than their neighbors are considered outliers.

Algorithm: 1. For each point, find its k nearest neighbors. 2. Compute reachability distances and local reachability density (LRD). 3. LOF score = average ratio of neighbor LRDs to this point's LRD. 4. LOF ≈ 1 means similar density as neighbors; LOF >> 1 means outlier.

fitPredict labels the training samples with their fitted LOF. predict, scoreSamples and decisionFunction evaluate arbitrary samples against the training set (novelty mode). A query point that coincides exactly with training points is scored as if those points were left out, so calling predict on training data without duplicate rows reproduces the fitted labels. This differs from scikit-learn, which counts a coinciding training point as a neighbor at distance 0.

With contamination: "auto" a sample is an outlier when its LOF is above 1.5; otherwise the threshold is the 1 - contamination quantile of the training LOF values.

Example
import { LocalOutlierFactor } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0, 0], [0.1, -0.1], [0.2, 0.1], [100, 100]]);const lof = new LocalOutlierFactor({ nNeighbors: 2, contamination: 0.25 });lof.fit(X);const labels = lof.predict(X); // -1 for outliers, 1 for inliers
Members (12)
  • constructor(options?: { readonly nNeighbors?: number; readonly contamination?: number | "auto"; })
  • negativeOutlierFactor: Tensor

    Opposite of the LOF of the training samples, shape (n_samples,).

  • negativeLofScores: Tensor

    Opposite of the LOF of the training samples.

  • offset: number

    Decision threshold in scoreSamples units: samples scoring below it are outliers.

  • fit(X: Tensor, _y?: Tensor): this

    Fit the model on the training data, computing k-distances, local reachability densities and the LOF of every training sample.

  • predict(X: Tensor): Tensor

    Predict whether each sample is an outlier relative to the training set.

  • fitPredict(X: Tensor, _y?: Tensor): Tensor

    Fit the model and label the training samples with their fitted LOF.

  • scoreSamples(X: Tensor): Tensor

    Opposite of the LOF of each sample (lower is more abnormal), computed against the training set.

  • decisionFunction(X: Tensor): Tensor

    Shifted opposite of the LOF: scoreSamples(X) - offset.

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

    Set parameters.

  • clone(): LocalOutlierFactor

    Create an unfitted copy with the same parameters.

CalibratedClassifierCV

Calibrated Classifier with Cross-Validation.

Wraps a base classifier and calibrates its probability predictions using either Platt scaling (sigmoid) or isotonic regression.

fit computes out-of-fold probabilities with stratified K-fold cross-validation (each fold uses a fresh clone of the base estimator), fits one calibrator per class on those probabilities, and finally fits the base estimator itself on all of the data. This matches scikit-learn's CalibratedClassifierCV(ensemble=False). Binary problems calibrate only the positive class and use 1 - p for the other; multiclass problems calibrate each class one-vs-rest and renormalize.

Note that the wrapped estimator instance is fitted in place, and that its constructor or clone() must be able to rebuild it from getParams().

Example
import { CalibratedClassifierCV, LogisticRegression } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X_train = tensor([[0.1, 1.2, 0.5], [0.4, 0.9, 1.1], [1.6, 0.2, 0.3], [1.9, 0.4, 0.8], [0.3, 1.5, 0.9], [2.1, 0.1, 0.4], [0.2, 1.1, 1.3], [1.7, 0.3, 0.2], [0.5, 1.4, 0.6], [2.2, 0.5, 0.7], [0.6, 1.0, 1.0], [1.8, 0.2, 0.5]]);const y_train = tensor([0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1], { dtype: 'int32' });const X_test = tensor([[0.3, 1.1, 0.8], [2.0, 0.3, 0.4]]); const base = new LogisticRegression();const cal = new CalibratedClassifierCV({ estimator: base, method: 'sigmoid' });cal.fit(X_train, y_train);const proba = cal.predictProba(X_test);
Members (9)
  • constructor(options: { readonly estimator: Classifier; readonly method?: "sigmoid" | "isotonic"; readonly cv?: number; })
  • classes: Tensor | undefined

    Class labels seen during fit in ascending order, or undefined before fit.

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

    Fit the calibrated classifier.

  • predict(X: Tensor): Tensor

    Predict class labels (the class with the highest calibrated probability).

  • predictProba(X: Tensor): Tensor

    Calibrated class probabilities.

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

    Mean accuracy of predict(X) against y.

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

    Set method or cv.

  • clone(): CalibratedClassifierCV

    Create an unfitted copy with the same parameters and a clone of the base estimator.

LinearDiscriminantAnalysis

Linear Discriminant Analysis (LDA).

A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using Bayes' rule. The model fits a Gaussian density to each class, assuming all classes share the same covariance matrix.

Can also be used for supervised dimensionality reduction by projecting data to the most discriminant directions.

Algorithm (same as scikit-learn's default svd solver): 1. Compute class means and the pooled within-class covariance (divided by n, as scikit-learn does) 2. Whiten the pooled covariance; directions with a numerically zero variance are dropped 3. Take the eigenvectors of the between-class scatter in the whitened space as discriminant directions, so projected data has identity within-class covariance 4. Classify with the log posterior under the shared covariance

Example
import { LinearDiscriminantAnalysis } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 2], [2, 1], [3, 3], [7, 8], [8, 7], [9, 9]]);const y = tensor([0, 0, 0, 1, 1, 1]); const lda = new LinearDiscriminantAnalysis();lda.fit(X, y);const predictions = lda.predict(tensor([[2, 3], [6, 7]]));
Members (16)
  • constructor(options?: { readonly nComponents?: number; readonly shrinkage?: number | "auto"; readonly priors?: readonly number[]; })
  • classes: Tensor | undefined

    Class labels seen during fit (sorted), or undefined before fitting.

  • explainedVarianceRatio: Float64Array | undefined

    Share of the between-class variance carried by each kept discriminant direction, relative to all directions (so the values may sum to less than 1 when nComponents is smaller than min(n_classes - 1, n_features)).

  • classMeans: Tensor

    Per-class feature means, shape (n_classes, n_features).

  • classPriors: Tensor

    Class prior probabilities, shape (n_classes,).

  • scalings: Tensor

    Projection matrix used by transform, shape (n_features, n_components).

  • nFeaturesIn: number

    Number of features seen during fit.

  • fit(X: Tensor, y: Tensor, sampleWeight?: undefined): this

    Fit the model.

  • predict(X: Tensor): Tensor

    Predict class labels.

  • predictProba(X: Tensor): Tensor

    Posterior class probabilities.

  • predictLogProba(X: Tensor): Tensor

    Log of the posterior class probabilities.

  • transform(X: Tensor): Tensor

    Project data to the most discriminant directions: (X - xbar) @ scalings.

  • fitTransform(X: Tensor, y?: Tensor): Tensor

    Fit the model and project the training data.

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

    Mean accuracy on the given data and labels.

  • getParams(): Record<string, unknown>

    Get hyperparameters for this estimator.

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

    Set the parameters of this estimator.

QuadraticDiscriminantAnalysis

Quadratic Discriminant Analysis (QDA).

A classifier with a quadratic decision boundary, generated by fitting class conditional densities to the data and using Bayes' rule. Unlike LDA, QDA fits a separate covariance matrix per class, allowing for more flexible (quadratic) decision boundaries.

Each class needs at least 2 samples (or regParam > 0). Class covariances are eigen-decomposed; eigenvalues below 1e-12 of the largest one are raised to that floor so that collinear features give finite, consistent scores (a warning is issued).

Example
import { QuadraticDiscriminantAnalysis } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 2], [2, 1], [3, 3], [7, 8], [8, 7], [9, 9]]);const y = tensor([0, 0, 0, 1, 1, 1]); const qda = new QuadraticDiscriminantAnalysis();qda.fit(X, y);const predictions = qda.predict(tensor([[2, 3], [6, 7]]));
Members (12)
  • constructor(options?: { readonly regParam?: number; readonly priors?: readonly number[]; })
  • classes: Tensor | undefined

    Class labels seen during fit (sorted), or undefined before fitting.

  • classMeans: Tensor

    Per-class feature means, shape (n_classes, n_features).

  • classPriors: Tensor

    Class prior probabilities, shape (n_classes,).

  • nFeaturesIn: number

    Number of features seen during fit.

  • fit(X: Tensor, y: Tensor, sampleWeight?: undefined): this

    Fit the model.

  • predict(X: Tensor): Tensor

    Predict class labels.

  • predictProba(X: Tensor): Tensor

    Posterior class probabilities.

  • predictLogProba(X: Tensor): Tensor

    Log of the posterior class probabilities.

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

    Mean accuracy on the given data and labels.

  • getParams(): Record<string, unknown>

    Get hyperparameters for this estimator.

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

    Set the parameters of this estimator.

GaussianProcessClassifier

Gaussian Process Classifier with RBF kernel.

Uses the Laplace approximation with Newton mode finding (Rasmussen & Williams, Algorithms 3.1 and 3.2), as scikit-learn does. For two classes it fits a single latent GP with a logistic link; for more classes it fits one binary problem per class (one-vs-rest) and normalizes the per-class probabilities. The predictive probability integrates the sigmoid over the posterior variance of the latent function, so it is less extreme than sigmoid(mean) far from the training data. Hyperparameters are fixed.

Example
import { GaussianProcessClassifier } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 1], [2, 2], [3, 3], [8, 8], [9, 9], [10, 10]]);const y = tensor([0, 0, 0, 1, 1, 1]); const gpc = new GaussianProcessClassifier();gpc.fit(X, y);const predictions = gpc.predict(X);const probabilities = gpc.predictProba(X);
Members (9)
  • constructor(options?: GaussianProcessClassifierOptions)
  • classes: Tensor | undefined

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

  • fit(X: Tensor, y: Tensor, sampleWeight?: undefined): this

    Fit the model.

  • predict(X: Tensor): Tensor
  • predictProba(X: Tensor): Tensor

    Class probabilities.

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

    Mean accuracy of predict(X) against y.

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

    Change hyperparameters.

  • clone(): GaussianProcessClassifier

    Create an unfitted copy with the same hyperparameters.

GaussianProcessRegressor

Gaussian Process Regressor with RBF kernel.

Matches scikit-learn's GaussianProcessRegressor with kernel ConstantKernel(kernelVariance) * RBF(lengthScale) and optimizer=None: the hyperparameters are used as given. The prior mean is zero (see normalizeY).

Example
import { GaussianProcessRegressor } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1], [2], [3], [4], [5]]);const y = tensor([1, 4, 9, 16, 25]);const gpr = new GaussianProcessRegressor({ alpha: 1e-6 });gpr.fit(X, y);const pred = gpr.predict(X);const { mean, std } = gpr.predictWithStd(X);
Members (9)
  • constructor(options?: GaussianProcessRegressorOptions)
  • fit(X: Tensor, y: Tensor, sampleWeight?: undefined): this

    Fit the model.

  • predict(X: Tensor): Tensor

    Posterior mean at the rows of X.

  • predictWithStd(X: Tensor): { mean: Tensor; std: Tensor; }

    Posterior mean and standard deviation at the rows of X.

  • logMarginalLikelihood(): number

    Log marginal likelihood of the training targets under the fitted kernel.

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

    Coefficient of determination R^2 of predict(X) against y.

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

    Change hyperparameters.

  • clone(): GaussianProcessRegressor

    Create an unfitted copy with the same hyperparameters.

MLPClassifier

Multi-layer Perceptron Classifier.

A feedforward neural network classifier trained with backpropagation (stochastic gradient descent, one sample per update). Binary problems use a single logistic output, problems with three or more classes use a softmax output; both minimize cross-entropy with L2 weight decay. Class labels must be integers.

Training stops when the epoch loss has not improved by more than tol for more than nIterNoChange consecutive epochs, or after maxIter epochs. Inputs should be standardized: unscaled features make plain SGD slow or unstable.

Example
import { MLPClassifier } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0, 0], [0, 1], [1, 0], [1, 1]]);const y = tensor([0, 1, 1, 0]); // XOR const clf = new MLPClassifier({ hiddenLayerSizes: [8], activation: 'tanh', learningRate: 0.1, maxIter: 1000, randomState: 0 });clf.fit(X, y);const predictions = clf.predict(X);
Members (12)
  • constructor(options?: MLPOptions)
  • classes: Tensor | undefined

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

  • nFeaturesIn: number

    Number of features seen during fit.

  • nIter: number

    Number of epochs run by the last fit.

  • lossCurve: number[]

    Mean cross-entropy of every epoch of the last fit.

  • loss: number

    Cross-entropy of the final epoch of the last fit.

  • fit(X: Tensor, y: Tensor, sampleWeightArg?: Tensor | void): this

    Train the network.

  • predict(X: Tensor): Tensor

    Predict class labels.

  • predictProba(X: Tensor): Tensor

    Predict class probabilities.

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

    Mean accuracy on the given data.

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

    Update hyperparameters.

MLPRegressor

Multi-layer Perceptron Regressor.

A feedforward neural network regressor trained with backpropagation (stochastic gradient descent, one sample per update). Uses an identity output and minimizes half the squared error with L2 weight decay. The target is standardized internally and predictions are mapped back to its original scale.

Training stops when the epoch loss (on the standardized target) has not improved by more than tol for more than nIterNoChange consecutive epochs, or after maxIter epochs. Inputs should be standardized.

Example
import { MLPRegressor } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1], [2], [3], [4], [5]]);const y = tensor([1.0, 4.0, 9.0, 16.0, 25.0]); const reg = new MLPRegressor({ hiddenLayerSizes: [10], learningRate: 0.01, maxIter: 500, randomState: 0 });reg.fit(X, y);const predictions = reg.predict(X);
Members (10)
  • constructor(options?: MLPOptions)
  • nFeaturesIn: number

    Number of features seen during fit.

  • nIter: number

    Number of epochs run by the last fit.

  • lossCurve: number[]

    Mean half squared error (on the standardized target) of every epoch of the last fit.

  • loss: number

    Loss of the final epoch of the last fit.

  • fit(X: Tensor, y: Tensor, sampleWeightArg?: Tensor | void): this

    Train the network.

  • predict(X: Tensor): Tensor

    Predict target values.

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

    Coefficient of determination R^2 on the given data.

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

    Update hyperparameters.

LabelPropagation

extends GraphLabelModel

Label Propagation algorithm.

Builds a fully connected graph over the training samples with RBF similarities exp(-gamma * ||x - x'||^2) and repeatedly replaces each unlabeled sample's label distribution by the similarity-weighted average of all samples' distributions. Labeled samples are clamped to their original label. Follows scikit-learn's LabelPropagation (RBF kernel).

Unlabeled samples must have label -1.

Example
import { LabelPropagation } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0,0],[1,0],[0,1],[1,1],[5,5],[6,5]]);const y = tensor([0, -1, -1, -1, 1, -1]); // -1 = unlabeledconst lp = new LabelPropagation();lp.fit(X, y);console.log(lp.predict(X));
Members (5)
  • constructor(options?: { readonly maxIter?: number; readonly tol?: number; readonly gamma?: number; })
  • fit(X: Tensor, y: Tensor): this

    Propagate the known labels to all training samples.

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

    Set hyperparameters.

  • clone(): LabelPropagation

    Create an unfitted copy with the same hyperparameters.

LabelSpreading

extends GraphLabelModel

Label Spreading algorithm.

Similar to LabelPropagation but uses the symmetrically normalized graph S = D^-1/2 W D^-1/2 (zero diagonal) and soft clamping. Each iteration computes Y = alpha * S Y + (1 - alpha) * Y0, where Y0 holds the original labels. alpha is the share of a sample's distribution that comes from its neighbors: at alpha = 0 nothing is propagated and unlabeled samples stay without a distribution; larger values let the graph dominate and the original labels fade (at alpha = 1 they are ignored entirely). Follows scikit-learn's LabelSpreading (RBF kernel).

Unlabeled samples must have label -1.

Example
import { LabelSpreading } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0,0],[1,0],[0,1],[1,1],[5,5],[6,5]]);const y = tensor([0, -1, -1, -1, 1, -1]); // -1 = unlabeledconst ls = new LabelSpreading({ alpha: 0.2 });ls.fit(X, y);console.log(ls.predict(X));
Members (5)
  • constructor(options?: { readonly maxIter?: number; readonly tol?: number; readonly gamma?: number; readonly alpha?: number; })
  • fit(X: Tensor, y: Tensor): this

    Spread the known labels to all training samples.

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

    Set hyperparameters.

  • clone(): LabelSpreading

    Create an unfitted copy with the same hyperparameters.

SelfTrainingClassifier

Self-Training Classifier.

A semi-supervised meta-estimator that iteratively labels unlabeled data using predictions from a supervised base classifier. In each iteration, the classifier is fit on all currently-labeled data, then the most confident predictions on unlabeled data are added to the labeled set: with criterion: "threshold" (default) those whose top class probability is strictly above threshold, with criterion: "kBest" the kBest most confident ones. Training stops when every sample is labeled, nothing was added in an iteration, or maxIter iterations ran. The final estimator is fit on the original labels plus all pseudo-labels.

Unlabeled samples should have label = -1. The base estimator is cloned, so the instance passed in is not modified (use estimator after fitting to inspect the fitted copy).

Example
import { SelfTrainingClassifier } from 'deepbox/ml';import { LogisticRegression } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0,0],[1,0],[0,1],[1,1],[5,5],[6,5],[5,6],[6,6]]);const y = tensor([0, -1, -1, -1, 1, -1, -1, -1]); // -1 = unlabeledconst base = new LogisticRegression();const st = new SelfTrainingClassifier({ baseEstimator: base });st.fit(X, y);st.predict(X);
Members (15)
  • constructor(options: { readonly baseEstimator: Classifier; readonly threshold?: number; readonly maxIter?: number; readonly criterion?: "threshold" | "kBest"; readonly kBest?: number; readonly verbose?: boolean; })
  • classes: Tensor

    Sorted class labels of the labeled training data.

  • estimator: Classifier

    The fitted copy of the base estimator.

  • nIterations: number

    Number of self-training iterations that ran during the last fit.

  • terminationCondition: SelfTrainingTermination

    Why the last fit stopped: "all_labeled", "no_change" or "max_iter".

  • transduction: Tensor

    Label of every training sample after self-training; -1 where no label was assigned.

  • labeledIterations: Int32Array

    Iteration in which each training sample received its label: 0 for samples that were labeled from the start, k for samples labeled in iteration k, and -1 for samples that never got a label.

  • transductionLabels: Int32Array | undefineddeprecated

    Per-sample iteration record in the original encoding: -1 for samples labeled from the start, -2 for samples that never got a label, otherwise the zero-based iteration.

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

    Fit the base classifier, adding confident pseudo-labels over several rounds.

  • predict(X: Tensor): Tensor

    Predict with the final base estimator.

  • predictProba(X: Tensor): Tensor

    Predict class probabilities with the final base estimator.

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

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

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

    Set hyperparameters.

  • clone(): SelfTrainingClassifier

    Create an unfitted copy with a cloned base estimator.

Functions

1

calibrationCurve

function calibrationCurve(yTrue: Tensor, yProb: Tensor, options?: { readonly nBins?: number; readonly strategy?: "uniform" | "quantile"; readonly posLabel?: number; }): { meanPredicted: number[]; fractionPositives: number[]; };

Compute calibration curve (reliability diagram data).

Details

Returns mean predicted probabilities and fraction of positives for each bin of predicted probability. Bins that contain no samples are omitted, so the returned arrays can be shorter than nBins.

Bins follow sklearn.calibration.calibration_curve: the first bin is [edge0, edge1] and the others are (lo, hi]. The default of 10 bins differs from scikit-learn's default of 5.

Parameters

yTrue
Tensor
True binary labels. Without posLabel the labels must be 0/1 (or -1/1, where 1 is positive)
yProb
Tensor
Predicted probabilities for the positive class, each in [0, 1]
optionsoptional
{ readonly nBins?: number; readonly strategy?: "uniform" | "quantile"; readonly posLabel?: number; }

Returns

{ meanPredicted: number[]; fractionPositives: number[]; }Object with meanPredicted and fractionPositives arrays

Throws

  • InvalidParameterErrorIf the sizes differ or an option is invalid
  • DataValidationErrorIf inputs are empty, probabilities are outside [0, 1] or labels are not binary
Example
import { calibrationCurve } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const yTrue = tensor([0, 0, 1, 1, 1]);const yProb = tensor([0.1, 0.3, 0.6, 0.8, 0.9]);const { meanPredicted, fractionPositives } = calibrationCurve(yTrue, yProb);
ml-advanced.ts
import {  CalibratedClassifierCV,  GaussianProcessRegressor,  IsolationForest,  LabelSpreading,  LogisticRegression,  MLPClassifier,} from "deepbox/ml";import { tensor } from "deepbox/ndarray"; const X = tensor([[1], [2], [3], [4], [5], [6]]);const y = tensor([0, 0, 0, 1, 1, 1]); const calibrated = new CalibratedClassifierCV({ estimator: new LogisticRegression(), cv: 2 }).fit(X, y);console.log(calibrated.predictProba(X).toString());console.log(new MLPClassifier({ hiddenLayerSizes: [8], randomState: 0 }).fit(X, y).predict(X).toString());console.log(new IsolationForest({ randomState: 0 }).fit(X).predict(X).toString()); // 1 inlier, -1 outlierconsole.log(new LabelSpreading().fit(X, tensor([0, -1, 0, 1, -1, 1])).predict(X).toString());console.log(new GaussianProcessRegressor().fit(X, tensor([1, 1.5, 2, 3, 3.5, 4])).predict(X).toString());