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 needspredictProbaand must be rebuildable fromgetParams().MLPClassifierandMLPRegressorare feed-forward networks trained with one-sample SGD updates. They are separate fromdeepbox/nn: they do not use autograd or devices. Standardize the inputs and passrandomState.IsolationForestandLocalOutlierFactordefault tocontamination: "auto".predictreturns 1 for inliers and -1 for outliers.- The semi-supervised estimators (
LabelPropagation,LabelSpreading,SelfTrainingClassifier) read -1 inyas an unlabeled sample. GaussianProcessRegressorandGaussianProcessClassifierfactor an n by n kernel matrix, so cost grows as O(n^3) in the number of training samples.
GaussianProcessClassifierOptions
typeOptions for GaussianProcessClassifier.
readonly alpha?: numberValue added to the diagonal of the training kernel matrix (default: 1e-5).
readonly lengthScale?: numberRBF kernel length scale (default: 1.0).
readonly kernelVariance?: numberRBF kernel variance (default: 1.0).
readonly maxLaplaceIter?: numberMaximum Newton iterations of the Laplace approximation, per binary problem (default: 100).
GaussianProcessRegressorOptions
typeOptions for GaussianProcessRegressor.
readonly alpha?: numberValue added to the diagonal of the kernel matrix, i.e.
readonly lengthScale?: numberRBF kernel length scale (default: 1.0).
readonly kernelVariance?: numberRBF kernel variance, the prior variance of the function (default: 1.0).
readonly normalizeY?: booleanSubtract the training mean and divide by the training standard deviation before fitting, and undo this in the predictions (default: false).
SelfTrainingTermination
typeWhy SelfTrainingClassifier stopped adding labels.
type SelfTrainingTermination = "max_iter" | "no_change" | "all_labeled";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.
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 inliersMembers (10)
constructor(options?: { readonly nEstimators?: number; readonly maxSamples?: number | "auto"; readonly contamination?: number | "auto"; readonly maxFeatures?: number; readonly randomState?: number; })offset: numberDecision threshold in
scoreSamplesunits: samples scoring below it are outliers.fit(X: Tensor, _y?: Tensor): thisFit the forest.
decisionFunction(X: Tensor): TensorOpposite of the anomaly score, shifted so that negative values are outliers.
predict(X: Tensor): TensorPredict whether each sample is an outlier.
fitPredict(X: Tensor, _y?: Tensor): TensorscoreSamples(X: Tensor): TensorAnomaly score of each sample (lower is more abnormal).
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisSet parameters.
clone(): IsolationForestCreate 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.
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 inliersMembers (12)
constructor(options?: { readonly nNeighbors?: number; readonly contamination?: number | "auto"; })negativeOutlierFactor: TensorOpposite of the LOF of the training samples, shape (n_samples,).
negativeLofScores: TensorOpposite of the LOF of the training samples.
offset: numberDecision threshold in
scoreSamplesunits: samples scoring below it are outliers.fit(X: Tensor, _y?: Tensor): thisFit the model on the training data, computing k-distances, local reachability densities and the LOF of every training sample.
predict(X: Tensor): TensorPredict whether each sample is an outlier relative to the training set.
fitPredict(X: Tensor, _y?: Tensor): TensorFit the model and label the training samples with their fitted LOF.
scoreSamples(X: Tensor): TensorOpposite of the LOF of each sample (lower is more abnormal), computed against the training set.
decisionFunction(X: Tensor): TensorShifted opposite of the LOF:
scoreSamples(X) - offset.getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisSet parameters.
clone(): LocalOutlierFactorCreate 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().
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 | undefinedClass labels seen during fit in ascending order, or
undefinedbefore fit.fit(X: Tensor, y: Tensor): thisFit the calibrated classifier.
predict(X: Tensor): TensorPredict class labels (the class with the highest calibrated probability).
predictProba(X: Tensor): TensorCalibrated class probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy of
predict(X)againsty.getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisSet
methodorcv.clone(): CalibratedClassifierCVCreate 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
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 | undefinedClass labels seen during fit (sorted), or
undefinedbefore fitting.explainedVarianceRatio: Float64Array | undefinedShare 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
nComponentsis smaller than min(n_classes - 1, n_features)).classMeans: TensorPer-class feature means, shape (n_classes, n_features).
classPriors: TensorClass prior probabilities, shape (n_classes,).
scalings: TensorProjection matrix used by
transform, shape (n_features, n_components).nFeaturesIn: numberNumber of features seen during fit.
fit(X: Tensor, y: Tensor, sampleWeight?: undefined): thisFit the model.
predict(X: Tensor): TensorPredict class labels.
predictProba(X: Tensor): TensorPosterior class probabilities.
predictLogProba(X: Tensor): TensorLog of the posterior class probabilities.
transform(X: Tensor): TensorProject data to the most discriminant directions:
(X - xbar) @ scalings.fitTransform(X: Tensor, y?: Tensor): TensorFit the model and project the training data.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data and labels.
getParams(): Record<string, unknown>Get hyperparameters for this estimator.
setParams(params: Record<string, unknown>): thisSet 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).
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 | undefinedClass labels seen during fit (sorted), or
undefinedbefore fitting.classMeans: TensorPer-class feature means, shape (n_classes, n_features).
classPriors: TensorClass prior probabilities, shape (n_classes,).
nFeaturesIn: numberNumber of features seen during fit.
fit(X: Tensor, y: Tensor, sampleWeight?: undefined): thisFit the model.
predict(X: Tensor): TensorPredict class labels.
predictProba(X: Tensor): TensorPosterior class probabilities.
predictLogProba(X: Tensor): TensorLog of the posterior class probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data and labels.
getParams(): Record<string, unknown>Get hyperparameters for this estimator.
setParams(params: Record<string, unknown>): thisSet 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.
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 | undefinedSorted class labels seen during
fit, orundefinedbefore fitting.fit(X: Tensor, y: Tensor, sampleWeight?: undefined): thisFit the model.
predict(X: Tensor): TensorpredictProba(X: Tensor): TensorClass probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy of
predict(X)againsty.getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisChange hyperparameters.
clone(): GaussianProcessClassifierCreate 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).
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): thisFit the model.
predict(X: Tensor): TensorPosterior mean at the rows of
X.predictWithStd(X: Tensor): { mean: Tensor; std: Tensor; }Posterior mean and standard deviation at the rows of
X.logMarginalLikelihood(): numberLog marginal likelihood of the training targets under the fitted kernel.
score(X: Tensor, y: Tensor): numberCoefficient of determination R^2 of
predict(X)againsty.getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisChange hyperparameters.
clone(): GaussianProcessRegressorCreate 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.
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 | undefinedSorted class labels seen during fit, or
undefinedbefore fitting.nFeaturesIn: numberNumber of features seen during
fit.nIter: numberNumber of epochs run by the last
fit.lossCurve: number[]Mean cross-entropy of every epoch of the last
fit.loss: numberCross-entropy of the final epoch of the last
fit.fit(X: Tensor, y: Tensor, sampleWeightArg?: Tensor | void): thisTrain the network.
predict(X: Tensor): TensorPredict class labels.
predictProba(X: Tensor): TensorPredict class probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate 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.
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: numberNumber of features seen during
fit.nIter: numberNumber 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: numberLoss of the final epoch of the last
fit.fit(X: Tensor, y: Tensor, sampleWeightArg?: Tensor | void): thisTrain the network.
predict(X: Tensor): TensorPredict target values.
score(X: Tensor, y: Tensor): numberCoefficient of determination R^2 on the given data.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate hyperparameters.
LabelPropagation
extends GraphLabelModelLabel 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.
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): thisPropagate the known labels to all training samples.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): LabelPropagationCreate an unfitted copy with the same hyperparameters.
LabelSpreading
extends GraphLabelModelLabel 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.
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): thisSpread the known labels to all training samples.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): LabelSpreadingCreate 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).
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: TensorSorted class labels of the labeled training data.
estimator: ClassifierThe fitted copy of the base estimator.
nIterations: numberNumber of self-training iterations that ran during the last fit.
terminationCondition: SelfTrainingTerminationWhy the last fit stopped: "all_labeled", "no_change" or "max_iter".
transduction: TensorLabel of every training sample after self-training; -1 where no label was assigned.
labeledIterations: Int32ArrayIteration in which each training sample received its label: 0 for samples that were labeled from the start,
kfor samples labeled in iterationk, and -1 for samples that never got a label.transductionLabels: Int32Array | undefineddeprecatedPer-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): thisFit the base classifier, adding confident pseudo-labels over several rounds.
predict(X: Tensor): TensorPredict with the final base estimator.
predictProba(X: Tensor): TensorPredict class probabilities with the final base estimator.
score(X: Tensor, y: Tensor): numberReturn the mean accuracy on the given test data and labels.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): SelfTrainingClassifierCreate an unfitted copy with a cloned base estimator.
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
yTrueTensor- True binary labels. Without
posLabelthe labels must be 0/1 (or -1/1, where 1 is positive) yProbTensor- 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 invalidDataValidationErrorIf inputs are empty, probabilities are outside [0, 1] or labels are not binary
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);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());Found a mistake? Open an issue.