deepbox/ml
Ensembles
AdaBoost, bagging, gradient boosting, stacking and voting estimators for classification and regression.
- Ensembles
Overview
Bagging*,AdaBoost*andGradientBoosting*grow decision trees internally, and there is no option to supply another base estimator.Voting*andStacking*take estimator instances inestimators. Class labels for the ensemble classifiers must be integers.- Defaults:
AdaBoostClassifieruses stumps (maxDepth: 1) and 50 rounds.BaggingClassifierbuilds 10 bootstrap trees without a depth limit.GradientBoosting*runs 100 stages withlearningRate: 0.1andmaxDepth: 3. VotingClassifierdefaults tovoting: "hard". Use"soft"to average probabilities, which needspredictProbaon every estimator.StackingClassifierandStackingRegressortrain the final estimator on out-of-fold predictions (cv: 5), then fit the base estimators you passed on all the data. They are fitted in place, so pass fresh instances. The default final estimators areLogisticRegressionandLinearRegression.
AdaBoostClassifierOptions
typeOptions of AdaBoostClassifier.
readonly nEstimators?: numberreadonly learningRate?: numberreadonly maxDepth?: numberreadonly randomState?: number
AdaBoostRegressorOptions
typeOptions of AdaBoostRegressor.
type AdaBoostRegressorOptions = AdaBoostClassifierOptions & { readonly loss?: "linear" | "square" | "exponential";};BaggingOptions
typeOptions shared by BaggingClassifier and BaggingRegressor.
readonly nEstimators?: numberreadonly maxSamples?: numberreadonly maxFeatures?: numberreadonly bootstrap?: booleanreadonly maxDepth?: numberreadonly randomState?: number
GradientBoostingClassifierOptions
typeOptions of GradientBoostingClassifier.
type GradientBoostingClassifierOptions = { readonly nEstimators?: number; readonly learningRate?: number; readonly maxDepth?: number; readonly minSamplesSplit?: number; readonly minSamplesLeaf?: number; readonly warmStart?: boolean; readonly subsample?: number; readonly maxFeatures?: "sqrt" | "log2" | number; readonly randomState?: number;} & BoostingTreeOptions;GradientBoostingLoss
typeLoss names accepted by GradientBoostingRegressor. "squared_error" and "absolute_error" are the scikit-learn spellings of "ls" and "lad".
type GradientBoostingLoss = RegressionLoss | "squared_error" | "absolute_error";GradientBoostingRegressorOptions
typeOptions of GradientBoostingRegressor.
type GradientBoostingRegressorOptions = { readonly nEstimators?: number; readonly learningRate?: number; readonly maxDepth?: number; readonly minSamplesSplit?: number; readonly minSamplesLeaf?: number; readonly warmStart?: boolean; readonly subsample?: number; readonly maxFeatures?: "sqrt" | "log2" | number; readonly validationFraction?: number; readonly nIterNoChange?: number; readonly loss?: GradientBoostingLoss; readonly alpha?: number; /* … */}StackingClassifierOptions
typeOptions of StackingClassifier.
readonly estimators: Classifier[]readonly finalEstimator?: Classifierreadonly passthrough?: booleanreadonly cv?: numberreadonly stackMethod?: StackingMethod
StackingMethod
typeWhich base-estimator output StackingClassifier feeds to the final estimator.
- "predictProba": class probabilities (one column for two classes, K columns otherwise) - "predict": the predicted label as a single column - "auto": "predictProba" when the estimator provides it, "predict" otherwise
type StackingMethod = "auto" | "predict" | "predictProba";StackingRegressorOptions
typeOptions of StackingRegressor.
readonly estimators: Regressor[]readonly finalEstimator?: Regressorreadonly passthrough?: booleanreadonly cv?: number
VotingClassifierOptions
typeOptions for VotingClassifier.
readonly estimators: readonly Classifier[]Classifier instances to combine.
readonly voting?: "hard" | "soft""hard"takes a weighted majority vote,"soft"averages predicted probabilities.readonly weights?: readonly number[]One non-negative weight per estimator, at least one of them positive.
VotingRegressorOptions
typeOptions for VotingRegressor.
readonly estimators: readonly Regressor[]Regressor instances to combine.
readonly weights?: readonly number[]One non-negative weight per estimator, at least one of them positive.
AdaBoostClassifier
AdaBoost Classifier (Adaptive Boosting).
Fits a sequence of weak classifiers (decision stumps by default) on re-weighted versions of the data, then combines them via weighted majority vote.
Algorithm: SAMME (Stagewise Additive Modeling using a Multi-class Exponential loss). The decision tree does not take sample weights, so each round trains the tree on a bootstrap sample drawn with probability proportional to the current weights, while the weighted error and the weight update use the full training set.
Fitting stops early when a round has zero weighted error (that tree gets weight 1) or when a tree is no better than random guessing. Class labels must be integers.
import { AdaBoostClassifier } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const clf = new AdaBoostClassifier({ nEstimators: 50, randomState: 0 });clf.fit(X_train, y_train);const predictions = clf.predict(X_test);Members (13)
constructor(options?: AdaBoostClassifierOptions)classes: Tensor | undefinedSorted class labels seen during fit, or
undefinedbefore fitting.nEstimatorsFitted: numberNumber of trees kept by the last fit (can be below
nEstimatorsafter an early stop).estimatorWeights: TensorWeight of each fitted tree in the vote.
featureImportances: TensorFeature importances: the mean of the trees' importances weighted by the tree weights, normalized to sum to one.
fit(X: Tensor, y: Tensor): thisFit the ensemble.
predict(X: Tensor): TensorPredict class labels by weighted majority vote (ties go to the smallest label).
decisionFunction(X: Tensor): TensorDecision function of the SAMME ensemble, following scikit-learn.
predictProba(X: Tensor): TensorPredict class probabilities, following scikit-learn: the softmax of the decision function divided by
K - 1(for two classes,sigmoid(decision)).score(X: Tensor, y: Tensor): numberMean accuracy on the given data.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisclone(): AdaBoostClassifierCreate an unfitted copy with the same hyperparameters.
AdaBoostRegressor
AdaBoost Regressor (Adaptive Boosting for Regression).
Uses the AdaBoost.R2 algorithm with decision tree regressors as base estimators and predicts the weighted median of the trees' predictions. As in the classifier, each tree is trained on a bootstrap sample drawn with probability proportional to the current sample weights.
import { AdaBoostRegressor } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const reg = new AdaBoostRegressor({ nEstimators: 50, randomState: 0 });reg.fit(X_train, y_train);const predictions = reg.predict(X_test);Members (10)
constructor(options?: AdaBoostRegressorOptions)nEstimatorsFitted: numberNumber of trees kept by the last fit (can be below
nEstimatorsafter an early stop).estimatorWeights: TensorWeight of each fitted tree in the weighted median.
featureImportances: TensorFeature importances: the mean of the trees' importances weighted by the tree weights, normalized to sum to one.
fit(X: Tensor, y: Tensor): thisFit the ensemble.
predict(X: Tensor): TensorPredict targets as the weighted median of the trees' predictions.
score(X: Tensor, y: Tensor): numberCoefficient of determination R^2 on the given data.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisclone(): AdaBoostRegressorCreate an unfitted copy with the same hyperparameters.
BaggingClassifier
Bagging Classifier (Bootstrap Aggregating).
Trains decision tree classifiers on random subsets of the rows and features and averages their predicted class probabilities. predict returns the class with the largest averaged probability, as scikit-learn's BaggingClassifier does.
Class labels must be integers. Fitting again discards the previous ensemble.
import { BaggingClassifier } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const clf = new BaggingClassifier({ nEstimators: 10, randomState: 0 });clf.fit(X_train, y_train);const predictions = clf.predict(X_test);Members (9)
constructor(options?: BaggingOptions)The number of rows and features drawn is
max(1, floor(fraction * n)), as in scikit-learn.classes: Tensor | undefinedSorted class labels seen during fit, or
undefinedbefore fitting.fit(X: Tensor, y: Tensor): thisFit the ensemble.
predict(X: Tensor): TensorPredict class labels: the class with the largest averaged tree probability (ties go to the smallest label).
predictProba(X: Tensor): TensorPredict class probabilities: the mean of the trees'
predictProba, with columns ordered like BaggingClassifier.classes.score(X: Tensor, y: Tensor): numberMean accuracy on the given data.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisclone(): BaggingClassifierCreate an unfitted copy with the same hyperparameters.
BaggingRegressor
Bagging Regressor (Bootstrap Aggregating for Regression).
Trains decision tree regressors on random subsets of the rows and features and averages their predictions. Fitting again discards the previous ensemble.
import { BaggingRegressor } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const reg = new BaggingRegressor({ nEstimators: 10, randomState: 0 });reg.fit(X_train, y_train);const predictions = reg.predict(X_test);Members (7)
constructor(options?: BaggingOptions)fit(X: Tensor, y: Tensor): thisFit the ensemble.
predict(X: Tensor): TensorPredict targets as the mean of the trees' predictions.
score(X: Tensor, y: Tensor): numberCoefficient of determination R^2 on the given data.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisclone(): BaggingRegressorCreate an unfitted copy with the same hyperparameters.
GradientBoostingClassifier
Gradient Boosting Classifier.
Uses gradient boosting with shallow regression trees for classification and the binomial deviance (log loss). The leaf values are Newton steps (Friedman's TreeBoost), computed on the rows each tree was trained on.
- Two classes: one boosted model on the log-odds, started from the log of the class ratio. - More classes: One-vs-Rest. One binary model is boosted per class, and probabilities are the per-class sigmoids normalized to sum to one. This differs from scikit-learn, which boosts all classes jointly with a multinomial deviance and a softmax.
Class labels must be integers. With subsample < 1 each stage trains on a random subset drawn without replacement.
import { GradientBoostingClassifier } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 2], [2, 3], [3, 1], [4, 2]]);const y = tensor([0, 0, 1, 1]); const gbc = new GradientBoostingClassifier({ nEstimators: 100, randomState: 0 });gbc.fit(X, y);const predictions = gbc.predict(X);Members (12)
constructor(options?: GradientBoostingClassifierOptions)classes: Tensor | undefinedSorted class labels seen during fit, or
undefinedbefore fitting.nEstimatorsFitted: numberNumber of boosting stages per binary model after the last fit.
featureImportances: TensorFeature importances averaged across all boosting stages and binary models.
fit(X: Tensor, y: Tensor, sampleWeightArg?: Tensor | void): thisFit the gradient boosting classifier.
decisionFunction(X: Tensor): TensorRaw (pre-sigmoid) scores of the boosted models.
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>): thisSet hyperparameters.
clone(): GradientBoostingClassifierCreate an unfitted copy with the same hyperparameters.
GradientBoostingRegressor
Gradient Boosting Regressor.
Builds an additive model in a forward stage-wise fashion using regression trees as weak learners. Each tree is fitted to the negative gradient of the loss; for the "lad", "huber" and "quantile" losses the leaf values are then replaced by the line-search optimum for that loss (leaf median, Huber-corrected median or leaf quantile of the residuals), as in Friedman's TreeBoost and scikit-learn.
Losses: "ls" squared error (initial value: the mean of y), "lad" absolute error (initial value: the median), "huber" (initial value: the median; the transition point is the alpha quantile of the absolute residuals) and "quantile" (initial value: the alpha quantile of y).
With subsample < 1 each stage trains on a random subset drawn without replacement. With nIterNoChange set, validationFraction of the rows are held out at random and boosting stops after nIterNoChange stages without a validation-loss improvement.
import { GradientBoostingRegressor } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1], [2], [3], [4], [5]]);const y = tensor([1.2, 2.1, 2.9, 4.0, 5.1]); const gbr = new GradientBoostingRegressor({ nEstimators: 100, randomState: 0 });gbr.fit(X, y);const predictions = gbr.predict(X);Members (9)
constructor(options?: GradientBoostingRegressorOptions)featureImportances: TensorFeature importances averaged across all boosting stages.
nEstimatorsFitted: numberNumber of stages actually fitted (below
nEstimatorsafter early stopping).fit(X: Tensor, y: Tensor, sampleWeightArg?: Tensor | void): thisFit the gradient boosting regressor.
predict(X: Tensor): TensorPredict target values: the initial value plus the scaled contribution of every tree.
score(X: Tensor, y: Tensor): numberCoefficient of determination R^2 on the given data.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisSet hyperparameters.
clone(): GradientBoostingRegressorCreate an unfitted copy with the same hyperparameters.
StackingClassifier
Stacking Classifier.
Combines multiple classifiers using a meta-learner (final estimator) that learns to combine the base estimators' outputs.
The meta-learner is trained on out-of-fold predictions: with cv folds (default 5, rows assigned to folds in turn, stratified by class), each base estimator is cloned and fitted on cv - 1 folds and predicts the remaining one. The base estimators passed to the constructor are then fitted on all the data (in place) and used at prediction time. Training the meta-learner on in-sample predictions instead would let it trust base estimators that memorized the training set. Set cv: 1 to do that anyway.
Two cases fall back to in-sample predictions for the affected rows: a fold whose training part has fewer than two classes, and datasets with fewer than two rows.
By default (stackMethod: "auto") the final estimator receives the base estimators' class probabilities: one column per estimator for two classes (the probability of the larger label), K columns per estimator otherwise.
Class labels must be integers.
import { StackingClassifier, DecisionTreeClassifier, LogisticRegression } from 'deepbox/ml'; const clf = new StackingClassifier({ estimators: [ new DecisionTreeClassifier({ maxDepth: 3 }), new DecisionTreeClassifier({ maxDepth: 5 }), ], finalEstimator: new LogisticRegression(),});clf.fit(X_train, y_train);const predictions = clf.predict(X_test);Members (9)
constructor(options: StackingClassifierOptions)classes: Tensor | undefinedSorted class labels seen during fit, or
undefinedbefore fitting.fit(X: Tensor, y: Tensor): thisFit the base estimators and the final estimator.
predict(X: Tensor): TensorPredict class labels with the final estimator.
predictProba(X: Tensor): TensorPredict class probabilities with the final estimator.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisSet
passthrough,cvorstackMethod.clone(): StackingClassifierCreate an unfitted copy with cloned base and final estimators and the same options.
StackingRegressor
Stacking Regressor.
Combines multiple regressors using a meta-learner (final estimator) that learns to combine the base estimators' predictions.
The meta-learner is trained on out-of-fold predictions: with cv folds (default 5, rows assigned to folds in turn), each base estimator is cloned and fitted on cv - 1 folds and predicts the remaining one. The base estimators passed to the constructor are then fitted on all the data (in place) and used at prediction time. Set cv: 1 to train the final estimator on in-sample predictions instead, which lets it trust base estimators that memorized the training set.
import { StackingRegressor, DecisionTreeRegressor, LinearRegression } from 'deepbox/ml'; const reg = new StackingRegressor({ estimators: [ new DecisionTreeRegressor({ maxDepth: 3 }), new DecisionTreeRegressor({ maxDepth: 5 }), ], finalEstimator: new LinearRegression(),});reg.fit(X_train, y_train);const predictions = reg.predict(X_test);Members (7)
constructor(options: StackingRegressorOptions)fit(X: Tensor, y: Tensor): thisFit the base estimators and the final estimator.
predict(X: Tensor): TensorPredict targets with the final estimator.
score(X: Tensor, y: Tensor): numberCoefficient of determination R^2 on the given data.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisSet
passthroughorcv.clone(): StackingRegressorCreate an unfitted copy with cloned base and final estimators and the same options.
VotingClassifier
Voting Classifier.
Combines multiple classifiers via weighted majority voting (hard) or weighted averaged probability (soft) voting. Hard voting resolves ties in favor of the smallest class label, like scikit-learn.
The estimators passed to the constructor are fitted in place (they are not cloned). Call VotingClassifier.clone to get an unfitted copy.
import { VotingClassifier, DecisionTreeClassifier, LogisticRegression } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0, 0], [1, 1], [8, 8], [9, 9]]);const y = tensor([0, 0, 1, 1]);const clf = new VotingClassifier({ estimators: [ new DecisionTreeClassifier({ maxDepth: 3 }), new LogisticRegression(), ], voting: 'hard',});clf.fit(X, y);const predictions = clf.predict(X);Members (9)
constructor(options: VotingClassifierOptions)classes: Tensor | undefinedSorted class labels seen during
fit, orundefinedbefore fitting.fit(X: Tensor, y: Tensor): thispredict(X: Tensor): TensorpredictProba(X: Tensor): TensorWeighted average of the estimators' class probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy of
predict(X)againsty.getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate
votingand/orweights.clone(): VotingClassifierCreate an unfitted copy with the same parameters and cloned estimators.
VotingRegressor
Voting Regressor.
Combines multiple regressors by averaging their predictions, optionally with per-estimator weights.
The estimators passed to the constructor are fitted in place (they are not cloned). Call VotingRegressor.clone to get an unfitted copy.
import { VotingRegressor, DecisionTreeRegressor, LinearRegression } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1], [2], [3], [4], [5]]);const y = tensor([1.1, 1.9, 3.2, 3.9, 5.1]);const reg = new VotingRegressor({ estimators: [ new DecisionTreeRegressor({ maxDepth: 3 }), new LinearRegression(), ],});reg.fit(X, y);const predictions = reg.predict(X);Members (7)
constructor(options: VotingRegressorOptions)fit(X: Tensor, y: Tensor): thispredict(X: Tensor): Tensorscore(X: Tensor, y: Tensor): numberCoefficient of determination R^2 of
predict(X)againsty.getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate
weights.clone(): VotingRegressorCreate an unfitted copy with the same parameters and cloned estimators.
import { AdaBoostClassifier, BaggingClassifier, DecisionTreeClassifier, GradientBoostingClassifier, LogisticRegression, StackingClassifier, VotingClassifier,} from "deepbox/ml";import { tensor } from "deepbox/ndarray"; const X = tensor([[1, 2], [2, 1], [3, 3], [4, 4], [5, 4], [6, 6]]);const y = tensor([0, 0, 0, 1, 1, 1]); console.log(new AdaBoostClassifier({ randomState: 1 }).fit(X, y).predict(X).toString());console.log(new BaggingClassifier({ randomState: 1 }).fit(X, y).predict(X).toString());console.log(new GradientBoostingClassifier({ randomState: 1 }).fit(X, y).predict(X).toString()); const voting = new VotingClassifier({ estimators: [new LogisticRegression(), new DecisionTreeClassifier({ maxDepth: 2 })], voting: "soft",});console.log(voting.fit(X, y).predict(X).toString()); const stack = new StackingClassifier({ estimators: [new LogisticRegression(), new DecisionTreeClassifier({ maxDepth: 2 })], cv: 2,});console.log(stack.fit(X, y).predict(X).toString());Found a mistake? Open an issue.