Skip to content

deepbox/ml

Ensembles

AdaBoost, bagging, gradient boosting, stacking and voting estimators for classification and regression.

  • Ensembles

Overview

  • Bagging*, AdaBoost* and GradientBoosting* grow decision trees internally, and there is no option to supply another base estimator. Voting* and Stacking* take estimator instances in estimators. Class labels for the ensemble classifiers must be integers.
  • Defaults: AdaBoostClassifier uses stumps (maxDepth: 1) and 50 rounds. BaggingClassifier builds 10 bootstrap trees without a depth limit. GradientBoosting* runs 100 stages with learningRate: 0.1 and maxDepth: 3.
  • VotingClassifier defaults to voting: "hard". Use "soft" to average probabilities, which needs predictProba on every estimator.
  • StackingClassifier and StackingRegressor train 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 are LogisticRegression and LinearRegression.

Types

11

AdaBoostClassifierOptions

type

Options of AdaBoostClassifier.

  • readonly nEstimators?: number
  • readonly learningRate?: number
  • readonly maxDepth?: number
  • readonly randomState?: number

AdaBoostRegressorOptions

type

Options of AdaBoostRegressor.

type AdaBoostRegressorOptions = AdaBoostClassifierOptions & {    readonly loss?: "linear" | "square" | "exponential";};

BaggingOptions

type

Options shared by BaggingClassifier and BaggingRegressor.

  • readonly nEstimators?: number
  • readonly maxSamples?: number
  • readonly maxFeatures?: number
  • readonly bootstrap?: boolean
  • readonly maxDepth?: number
  • readonly randomState?: number

GradientBoostingClassifierOptions

type

Options 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

type

Loss 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

type

Options 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

type

Options of StackingClassifier.

  • readonly estimators: Classifier[]
  • readonly finalEstimator?: Classifier
  • readonly passthrough?: boolean
  • readonly cv?: number
  • readonly stackMethod?: StackingMethod

StackingMethod

type

Which 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

type

Options of StackingRegressor.

  • readonly estimators: Regressor[]
  • readonly finalEstimator?: Regressor
  • readonly passthrough?: boolean
  • readonly cv?: number

VotingClassifierOptions

type

Options 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

type

Options 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.

Classes

10

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.

Example
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 | undefined

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

  • nEstimatorsFitted: number

    Number of trees kept by the last fit (can be below nEstimators after an early stop).

  • estimatorWeights: Tensor

    Weight of each fitted tree in the vote.

  • featureImportances: Tensor

    Feature importances: the mean of the trees' importances weighted by the tree weights, normalized to sum to one.

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

    Fit the ensemble.

  • predict(X: Tensor): Tensor

    Predict class labels by weighted majority vote (ties go to the smallest label).

  • decisionFunction(X: Tensor): Tensor

    Decision function of the SAMME ensemble, following scikit-learn.

  • predictProba(X: Tensor): Tensor

    Predict 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): number

    Mean accuracy on the given data.

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

    Create 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.

Example
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: number

    Number of trees kept by the last fit (can be below nEstimators after an early stop).

  • estimatorWeights: Tensor

    Weight of each fitted tree in the weighted median.

  • featureImportances: Tensor

    Feature importances: the mean of the trees' importances weighted by the tree weights, normalized to sum to one.

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

    Fit the ensemble.

  • predict(X: Tensor): Tensor

    Predict targets as the weighted median of the trees' predictions.

  • 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
  • clone(): AdaBoostRegressor

    Create 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.

Example
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 | undefined

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

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

    Fit the ensemble.

  • predict(X: Tensor): Tensor

    Predict class labels: the class with the largest averaged tree probability (ties go to the smallest label).

  • predictProba(X: Tensor): Tensor

    Predict class probabilities: the mean of the trees' predictProba, with columns ordered like BaggingClassifier.classes.

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

    Mean accuracy on the given data.

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

    Create 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.

Example
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): this

    Fit the ensemble.

  • predict(X: Tensor): Tensor

    Predict targets as the mean of the trees' predictions.

  • 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
  • clone(): BaggingRegressor

    Create 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.

Example
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 | undefined

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

  • nEstimatorsFitted: number

    Number of boosting stages per binary model after the last fit.

  • featureImportances: Tensor

    Feature importances averaged across all boosting stages and binary models.

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

    Fit the gradient boosting classifier.

  • decisionFunction(X: Tensor): Tensor

    Raw (pre-sigmoid) scores of the boosted models.

  • 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

    Set hyperparameters.

  • clone(): GradientBoostingClassifier

    Create 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.

Example
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: Tensor

    Feature importances averaged across all boosting stages.

  • nEstimatorsFitted: number

    Number of stages actually fitted (below nEstimators after early stopping).

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

    Fit the gradient boosting regressor.

  • predict(X: Tensor): Tensor

    Predict target values: the initial value plus the scaled contribution of every tree.

  • 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

    Set hyperparameters.

  • clone(): GradientBoostingRegressor

    Create 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.

Example
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 | undefined

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

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

    Fit the base estimators and the final estimator.

  • predict(X: Tensor): Tensor

    Predict class labels with the final estimator.

  • predictProba(X: Tensor): Tensor

    Predict class probabilities with the final estimator.

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

    Mean accuracy on the given data.

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

    Set passthrough, cv or stackMethod.

  • clone(): StackingClassifier

    Create 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.

Example
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): this

    Fit the base estimators and the final estimator.

  • predict(X: Tensor): Tensor

    Predict targets with the final estimator.

  • 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

    Set passthrough or cv.

  • clone(): StackingRegressor

    Create 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.

Example
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 | undefined

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

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

    Weighted average of the estimators' 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

    Update voting and/or weights.

  • clone(): VotingClassifier

    Create 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.

Example
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): this
  • predict(X: Tensor): Tensor
  • 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

    Update weights.

  • clone(): VotingRegressor

    Create an unfitted copy with the same parameters and cloned estimators.

ml-ensemble.ts
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());