Skip to content

deepbox/ml

Pipelines & Model Selection

Pipeline, ColumnTransformer and FeatureUnion, cross-validation, grid and randomized search, multiclass wrappers, estimator tags and permutation importance.

  • Workflow

Overview

  • Pipeline takes [name, step] pairs. Each transformer feeds the next step, and the last step is the estimator. Step names must not contain __, which separates a step name from its parameter in keys such as scaler__withMean.
  • crossValScore(estimator, X, y, cv, scoring?) takes the number of folds as cv, an integer of at least 2, not a splitter object. Folds come from a fixed-seed shuffle, so results repeat, and classifiers get stratified folds. crossValidate returns { testScores, fitTime, scoreTime } and accepts several scorers.
  • GridSearchCV(estimator, paramGrid, { cv, scoring }) and RandomizedSearchCV clone the estimator for each candidate and refit the best one on all the data. Read bestParams, bestScore, bestEstimator and cvResults. Keys in the grid are constructor options such as maxIter.
  • setOutput and getOutput store a preference only. The built-in estimators always return tensors.
  • permutationImportance(model, X, y) measures how much the score drops when a feature is shuffled. The deprecated names cross_val_score and cross_validate still work.

Types

18

Classifier

type

Type for classification models.

Classifiers predict discrete class labels.

type Classifier = Estimator & {    fit(X: Tensor, y: Tensor): Classifier;    predict(X: Tensor): Tensor;    predictProba(X: Tensor): Tensor;    score(X: Tensor, y: Tensor): number;    readonly classes?: Tensor | undefined;};

Clusterer

type

Type for clustering models.

Clusterers group similar samples together.

type Clusterer = Estimator<void> & {    fit(X: Tensor, y?: Tensor): Clusterer;    predict(X: Tensor): Tensor;    fitPredict(X: Tensor, y?: Tensor): Tensor;    readonly clusterCenters?: Tensor;    readonly labels?: Tensor;};

Estimator

type

Base type for all estimators (models) in Deepbox.

  • fit(X: Tensor, y?: Tensor, params?: FitParams): Estimator<FitParams>

    Fit the model to training data.

  • getParams(): Record<string, unknown>

    Get parameters for this estimator.

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

    Set parameters for this estimator.

  • clone?(): Estimator<FitParams>

    Create a fresh unfitted clone of this estimator with the same parameters.

EstimatorTags

type

Metadata tags describing estimator capabilities and requirements.

Inspired by scikit-learn's estimator tags, these provide machine-readable metadata about what an estimator supports or requires.

  • readonly estimatorType: "classifier" | "regressor" | "clusterer" | "transformer" | "outlier_detector"

    Estimator type: "classifier", "regressor", "clusterer", "transformer", "outlier_detector"

  • readonly multiOutput: boolean

    Whether the estimator supports multi-output targets

  • readonly requiresPositiveX: boolean

    Whether the estimator requires all features to be non-negative

  • readonly requiresPositiveY: boolean

    Whether the estimator requires the target to be non-negative

  • readonly supportsSparse: boolean

    Whether the estimator supports sparse input

  • readonly supportsSampleWeight: boolean

    Whether the estimator supports sample weights

  • readonly hasPredictProba: boolean

    Whether the estimator has a predict_proba method

  • readonly hasDecisionFunction: boolean

    Whether the estimator has a decision_function method

  • readonly requiresY: boolean

    Whether fit requires y (false for unsupervised)

OutlierDetector

type

Type for outlier/anomaly detection models.

type OutlierDetector = Estimator<void> & {    fit(X: Tensor, y?: Tensor): OutlierDetector;    predict(X: Tensor): Tensor;    fitPredict(X: Tensor, y?: Tensor): Tensor;    scoreSamples(X: Tensor): Tensor;    decisionFunction?(X: Tensor): Tensor;};

OutputType

type

Output format for estimator transform/predict results.

- "default": Return Tensor (the standard behavior) - "array": Return plain nested number arrays (advisory: built-in estimators always return Tensors)

type OutputType = "default" | "array";

Regressor

type

Type for regression models.

Regressors predict continuous values.

type Regressor = Estimator & {    fit(X: Tensor, y: Tensor): Regressor;    predict(X: Tensor): Tensor;    score(X: Tensor, y: Tensor): number;};

Transformer

type

Type for transformer models.

Transformers modify or transform the input data.

type Transformer = Estimator<void> & {    fit(X: Tensor, y?: Tensor): Transformer;    transform(X: Tensor): Tensor;    fitTransform(X: Tensor, y?: Tensor): Tensor;    inverseTransform?(X: Tensor): Tensor;};

PermutationImportanceOptions

type

Options for permutationImportance.

  • readonly nRepeats?: number

    Number of shuffles per feature (default: 5).

  • readonly randomState?: number

    Seed for the shuffles.

  • readonly scoring?: (estimator: Scorable, X: Tensor, y: Tensor) => number

    Custom score function where larger is better (default: estimator.score(X, y)).

PermutationImportanceResult

type

Result of a permutation importance computation.

Note that importances is laid out as (n_repeats, n_features), the transpose of scikit-learn's (n_features, n_repeats).

  • readonly importancesMean: Tensor

    Mean importance for each feature (shape: [n_features]).

  • readonly importancesStd: Tensor

    Standard deviation of the importance for each feature, with ddof = 0 (shape: [n_features]).

  • readonly importances: Tensor

    Raw importances matrix (shape: [n_repeats, n_features]).

CrossValidateResult

type

Result of cross_validate().

  • readonly testScores: Record<string, number[]>

    Array of test scores per fold for each scoring metric

  • readonly fitTime: number[]

    Array of fit times per fold (ms)

  • readonly scoreTime: number[]

    Array of score times per fold (ms)

CrossValidator

type

Anything that yields train/test index splits, such as the splitters of deepbox/preprocess (KFold, StratifiedKFold, GroupKFold, TimeSeriesSplit, ...). y and groups are only passed on; a splitter ignores the ones it does not need.

  • split(X: Tensor, y?: Tensor, groups?: CvGroups): Iterable<CvSplit>

CrossValScoreOptions

type

Options object accepted as the 4th argument of cross_val_score.

type CrossValScoreOptions = CvOptions & {    cv?: CvSpec;    scoring?: Scorer;};

CvGroups

type

Group label per sample, as a 1-D tensor or an array.

type CvGroups = Tensor | readonly (string | number | bigint)[];

CvOptions

type

Options shared by the cross-validation helpers.

  • groups?: CvGroups | undefined

    Group label per sample, forwarded to a splitter that uses groups (ignored for integer cv).

  • shuffle?: boolean | undefined

    For integer cv: shuffle the samples before building folds (default: true).

  • randomState?: number | undefined

    For integer cv with shuffle: seed of the shuffle (default: 0).

CvSpec

type

Cross-validation strategy: a number of folds, or a splitter object.

type CvSpec = number | CrossValidator;

CvSplit

type

One train/test split, as index lists into the rows of X.

  • readonly trainIndex: ArrayLike<number>
  • readonly testIndex: ArrayLike<number>

GridSearchResult

type

Result of a single parameter combination evaluation

  • readonly params: Record<string, unknown>
  • readonly meanScore: number
  • readonly scores: number[]

Classes

7

GridSearchCV

Exhaustive search over specified parameter values for an estimator.

Every combination of the listed values is cross-validated (see cross_val_score for how folds are built) and the best one, by mean score, is refitted on the whole data set. Ties go to the first combination.

Example
import { GridSearchCV } from 'deepbox/ml';import { Ridge } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = 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 = tensor([0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1], { dtype: 'int32' }); const gs = new GridSearchCV(new Ridge(), { alpha: [0.1, 1, 10] }, { cv: 5 });gs.fit(X, y);console.log(gs.bestParams);console.log(gs.bestScore);
Members (12)
  • constructor(estimator: Estimator, paramGrid: Record<string, unknown[]>, options?: { cv?: CvSpec; shuffle?: boolean; randomState?: number; scoring?: Scorer; })
  • bestParams: Record<string, unknown>

    Best parameters found

  • bestScore: number

    Best mean CV score

  • bestEstimator: Estimator | undefined

    Best fitted estimator, refitted on all of the data

  • cvResults: GridSearchResult[]

    All CV results, in the order the combinations were evaluated

  • bestIndex: number

    Index of the best combination in cvResults (-1 before fitting)

  • fit(X: Tensor, y: Tensor, groups?: CvGroups): this

    Cross-validate every combination and refit the best one.

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

    Class probabilities of the best estimator.

  • score(X: Tensor, y: Tensor): number
  • getParams(): Record<string, unknown>
  • setParams(params: Record<string, unknown>): this

    Update the search configuration.

RandomizedSearchCV

Randomized search over parameter distributions.

Samples nIter distinct parameter combinations (without replacement) from the grid of listed values instead of trying all of them, cross-validates each and refits the best one on the whole data set. If the grid has at most nIter combinations, all of them are evaluated.

Example
import { RandomizedSearchCV } from 'deepbox/ml';import { Ridge } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = 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 = tensor([0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1], { dtype: 'int32' }); const rs = new RandomizedSearchCV(  new Ridge(),  { alpha: [0.01, 0.1, 1, 10, 100] },  { nIter: 3, cv: 5 });rs.fit(X, y);
Members (12)
  • constructor(estimator: Estimator, paramDistributions: Record<string, unknown[]>, options?: { nIter?: number; cv?: CvSpec; shuffle?: boolean; cvRandomState?: number; randomState?: number; scoring?: Scorer; })
  • bestParams: Record<string, unknown>

    Best parameters found

  • bestScore: number

    Best mean CV score

  • bestEstimator: Estimator | undefined

    Best fitted estimator, refitted on all of the data

  • cvResults: GridSearchResult[]

    CV results of the sampled combinations, in sampling order

  • bestIndex: number

    Index of the best combination in cvResults (-1 before fitting)

  • fit(X: Tensor, y: Tensor, groups?: CvGroups): this

    Cross-validate the sampled combinations and refit the best one.

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

    Class probabilities of the best estimator.

  • score(X: Tensor, y: Tensor): number
  • getParams(): Record<string, unknown>
  • setParams(params: Record<string, unknown>): this

    Update the search configuration.

OneVsOneClassifier

One-vs-One (OvO) multiclass strategy.

Fits one classifier for each pair of classes (the lower label of the pair is passed to the binary estimator as 0, the higher as 1). Each pairwise classifier votes for one class. Ties between classes with equal votes are broken by the summed pairwise confidences (decisionFunction, or the positive-class probability when the base estimator has no decision function), as in scikit-learn.

Example
import { OneVsOneClassifier, LinearSVC } 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 ovo = new OneVsOneClassifier({ estimator: new LinearSVC() });ovo.fit(X_train, y_train);const pred = ovo.predict(X_test);
Members (10)
  • constructor(options: BinaryEstimatorOptions)
  • classes: Tensor

    Sorted class labels seen during fit.

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

    Fit one binary classifier for every pair of classes.

  • predict(X: Tensor): Tensor

    Predict class labels by majority vote of the pairwise classifiers.

  • decisionFunction(X: Tensor): Tensor

    Vote counts plus a small confidence-based tie-breaker, one column per class.

  • predictProba(X: Tensor): Tensor

    Estimate class probabilities using normalized vote counts.

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

    Mean accuracy on the given data and labels.

  • getParams(): Record<string, unknown>

    Parameters of this estimator: the template estimator.

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

    Replace the template estimator.

  • clone(): OneVsOneClassifier

    Create an unfitted copy with a cloned template estimator.

OneVsRestClassifier

One-vs-Rest (OvR) multiclass strategy.

Fits one binary classifier per class. For class k, the positive examples are from class k and negative examples are all other classes.

Prediction picks the class whose binary classifier is most confident. The confidence is the estimator's decisionFunction when it has one, otherwise the positive-class column of predictProba, otherwise its hard 0/1 predict output (ties go to the smallest label). Each binary problem uses labels 0 (rest) and 1 (class k).

Example
import { OneVsRestClassifier, 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 ovr = new OneVsRestClassifier({ estimator: new LogisticRegression() });ovr.fit(X_train, y_train);const pred = ovr.predict(X_test);
Members (10)
  • constructor(options: BinaryEstimatorOptions)
  • classes: Tensor

    Sorted class labels seen during fit.

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

    Fit one binary classifier per class.

  • predict(X: Tensor): Tensor

    Predict class labels.

  • decisionFunction(X: Tensor): Tensor

    Confidence score of every class, one column per class.

  • predictProba(X: Tensor): Tensor

    Estimate class probabilities.

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

    Mean accuracy on the given data and labels.

  • getParams(): Record<string, unknown>

    Parameters of this estimator: the template estimator.

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

    Replace the template estimator.

  • clone(): OneVsRestClassifier

    Create an unfitted copy with a cloned template estimator.

ColumnTransformer

ColumnTransformer applies transformers to specific column subsets of the data.

Each transformer is applied to a specified subset of columns, and the results are concatenated horizontally. This is useful when different feature types require different preprocessing. A spec with an empty column list is skipped. The output is float64.

Example
import { ColumnTransformer } from 'deepbox/ml';import { StandardScaler, OneHotEncoder } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; // Columns 0 to 2 are numeric, columns 3 and 4 hold category codes.const X = tensor([  [0.1, 1.2, 0.5, 0, 1],  [0.4, 0.9, 1.1, 1, 0],  [1.6, 0.2, 0.3, 2, 1],  [1.9, 0.4, 0.8, 0, 0],]); const ct = new ColumnTransformer([  ['num', new StandardScaler(), [0, 1, 2]],  ['cat', new OneHotEncoder(), [3, 4]],]);const Xt = ct.fitTransform(X);
Members (8)
  • constructor(transformers: ReadonlyArray<readonly [ string, Transformer | "passthrough" | "drop", number[] ]>, options?: { readonly remainder?: "drop" | "passthrough"; })
  • transformerNames: string[]
  • fit(X: Tensor, y?: Tensor): this

    Fit every transformer on its column subset.

  • transform(X: Tensor): Tensor

    Transform X column group by column group and concatenate the results.

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

    Fit and transform in one call.

  • getParams(): Record<string, unknown>

    Remainder mode plus the parameters of every transformer, keyed by transformer name.

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

    Set remainder, replace a spec's transformer with "passthrough" or "drop", or set transformer parameters with { name: { param: value } } or { name__param: value }.

  • clone(): ColumnTransformer

    Create an unfitted copy whose transformers are fresh clones.

FeatureUnion

Concatenate results of multiple transformer objects.

Applies each transformer independently and concatenates the results column-wise. Useful for combining multiple feature extraction mechanisms into a single transformer. The output is float64.

Example
import { FeatureUnion } from 'deepbox/ml';import { PolynomialFeatures, Binarizer } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const X = 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 union = new FeatureUnion([  ['poly', new PolynomialFeatures({ degree: 2 })],  ['bin', new Binarizer({ threshold: 0.5 })],]);const Xt = union.fitTransform(X);
Members (8)
  • constructor(transformers: ReadonlyArray<readonly [ string, Transformer ]>)
  • transformerNames: string[]
  • fit(X: Tensor, y?: Tensor): this

    Fit every transformer on X.

  • transform(X: Tensor): Tensor

    Transform X with every transformer and concatenate the outputs column-wise.

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

    Fit every transformer and return the concatenated outputs.

  • getParams(): Record<string, unknown>

    Parameters of every transformer, keyed by transformer name.

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

    Set transformer parameters with { name: { param: value } } or { name__param: value }.

  • clone(): FeatureUnion

    Create an unfitted copy whose transformers are fresh clones.

Pipeline

Pipeline of transforms with a final estimator.

Sequentially applies a list of transforms and a final estimator. Intermediate steps must implement transform(). The final step can be any estimator (classifier, regressor, transformer, etc.).

Step parameters can be changed through setParams with the step name and the parameter joined by two underscores, for example { scaler__withMean: false }. This also lets a Pipeline be tuned by GridSearchCV.

Example
import { Pipeline } from 'deepbox/ml';import { StandardScaler } from 'deepbox/preprocess';import { 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 pipe = new Pipeline([  ['scaler', new StandardScaler()],  ['clf', new LogisticRegression()],]);pipe.fit(X_train, y_train);const pred = pipe.predict(X_test);
Members (16)
  • constructor(steps: ReadonlyArray<readonly [ string, Estimator | Transformer ]>)
  • stepNames: string[]

    Get all step names.

  • classes: Tensor | undefined

    Class labels of the final step, or undefined if it does not expose any.

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

    Fit all steps.

  • transform(X: Tensor): Tensor

    Transform data through all steps (final step must be a transformer).

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

    Fit and transform (final step must be a transformer).

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

    Fit the pipeline and return the final step's predictions for X.

  • predict(X: Tensor): Tensor

    Transform data through intermediate steps, then predict with final step.

  • predictProba(X: Tensor): Tensor

    Transform data through intermediate steps, then predict probabilities.

  • decisionFunction(X: Tensor): Tensor

    Transform data through intermediate steps, then compute the final step's decision function.

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

    Transform data through intermediate steps, then score with final step.

  • inverseTransform(X: Tensor): Tensor

    Map transformed data back to the original feature space, undoing the steps in reverse order.

  • getStep(name: string): Estimator | Transformer

    Get a named step by name.

  • getParams(): Record<string, unknown>

    Parameters of every step, keyed by step name.

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

    Set step parameters.

  • clone(): Pipeline

    Create a fresh, unfitted clone of this pipeline with freshly cloned steps.

Functions

9

assertEstimator

function assertEstimator<T extends Estimator>(value: T): T;

Runtime helper to validate estimator-like objects.

Parameters

value
T
Candidate estimator

Returns

Tvalue unchanged, typed as an estimator

Throws

  • InvalidParameterErrorIf value is not an object or lacks fit, getParams or setParams

getEstimatorTags

function getEstimatorTags(estimator: Estimator): EstimatorTags;

Get estimator tags from an estimator, using sensible defaults based on the estimator's interface.

If the estimator implements _getTags(), those are used. Otherwise, tags are inferred from the estimator's methods.

Parameters

estimator
Estimator
The estimator to get tags for

Returns

EstimatorTagsEstimator tags

getOutput

function getOutput(): OutputType;

Get the current global output type setting (see set_output).

Returns

OutputTypeCurrent output type

resetOutput

function resetOutput(): void;

Reset the output type to default (Tensor).

setOutput

function setOutput(outputType: OutputType): void;

Set the global output type preference.

The value is stored here and read back with get_output. The built-in estimators always return Tensors; use tensor.toArray() to get plain nested arrays. Custom estimators and wrappers can consult get_output() to decide what to return.

Parameters

outputType
OutputType
"default" for Tensor, "array" for plain nested number arrays

Throws

  • InvalidParameterErrorIf outputType is not "default" or "array"
Example
import { setOutput, getOutput } from 'deepbox/ml'; setOutput('array');getOutput(); // 'array' (custom estimators can read this to decide what to return)setOutput('default');

permutationImportance

function permutationImportance(estimator: Scorable, X: Tensor, y: Tensor, options?: PermutationImportanceOptions): PermutationImportanceResult;

Permutation feature importance.

Details

Measures the decrease in a model's score when a single feature value is randomly shuffled. A large decrease indicates the model relies heavily on that feature.

X is never modified. Each importance is baselineScore - permutedScore, so a feature the model ignores has an importance near 0 and a negative value means the shuffled feature happened to score slightly better.

Parameters

estimator
Scorable
A fitted estimator with a score(X, y) method
X
Tensor
Test features of shape (n_samples, n_features)
y
Tensor
Test labels/targets of shape (n_samples,)
optionsoptional
PermutationImportanceOptions
Configuration options

Returns

PermutationImportanceResultPermutation importance result

Throws

  • ShapeErrorIf X is not 2-D, y is not 1-D, or their sample counts differ
  • DataValidationErrorIf X has no samples or no features
  • InvalidParameterErrorIf nRepeats is not an integer >= 1, or estimator has no score method and no scoring function is given
Example
import { permutationImportance, LinearRegression } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 5], [2, 3], [3, 8], [4, 1], [5, 9], [6, 2]]);const y = tensor([2, 4, 6, 8, 10, 12]);const model = new LinearRegression();model.fit(X, y);const result = permutationImportance(model, X, y, { nRepeats: 10, randomState: 0 });console.log(result.importancesMean);

crossValidate

function crossValidate(estimator: Estimator, X: Tensor, y: Tensor, options?: CvOptions & { cv?: CvSpec; scoring?: Record<string, Scorer> | Scorer; }): CrossValidateResult;

Evaluate an estimator using cross-validation with multiple metrics.

Unlike cross_val_score which returns only scores for a single metric, cross_validate supports multiple scoring functions and also reports fit/score times. Folds are built as in cross_val_score: options.cv is a number of folds or a splitter object, and options.groups, options.shuffle and options.randomState behave as there.

Parameters

estimator
Estimator
Estimator with fit and score methods
X
Tensor
Features of shape (n_samples, n_features)
y
Tensor
Targets of shape (n_samples,)
optionsoptional
CvOptions & { cv?: CvSpec; scoring?: Record<string, Scorer> | Scorer; }
Configuration options (cv, scoring, groups, shuffle, randomState)

Returns

CrossValidateResultObject with testScores (per metric), fitTime, and scoreTime arrays

Throws

  • InvalidParameterErrorIf cv is invalid, scoring is empty or holds a non-function, or no scorer is available
Example
import { crossValidate, LogisticRegression } from 'deepbox/ml';import { accuracy } from 'deepbox/metrics';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0.1, 1.2], [0.4, 0.9], [1.6, 0.2], [1.9, 0.4], [0.3, 1.5], [2.1, 0.1], [0.2, 1.1], [1.7, 0.3], [0.5, 1.4], [2.2, 0.5]]);const y = tensor([0, 0, 1, 1, 0, 1, 0, 1, 0, 1], { dtype: 'int32' }); // Single metric (uses estimator.score)const single = crossValidate(new LogisticRegression(), X, y, { cv: 5 });console.log(single.testScores['score']); // Multiple metricsconst multi = crossValidate(new LogisticRegression(), X, y, {  cv: 5,  scoring: {    score: (est, Xv, yv) => est.score(Xv, yv),    accuracy: (est, Xv, yv) => accuracy(yv, est.predict(Xv)),  },});console.log(multi.testScores['accuracy']);

crossValScore

function crossValScore(estimator: Estimator, X: Tensor, y: Tensor, cv?: CvSpec | CrossValScoreOptions, scoring?: Scorer, options?: CvOptions): number[];

Evaluate an estimator using cross-validation.

Details

With an integer cv the data is split into cv folds, the estimator is trained on cv - 1 of them and scored on the remaining one. The folds come from a shuffle with a fixed seed (set shuffle: false for contiguous folds like scikit-learn's KFold, or randomState for another seed), so results are reproducible. For classifiers (estimators exposing classes or predictProba) the folds are stratified by the labels in y. Fold sizes differ by at most one sample.

cv may also be any splitter object with a split(X, y?, groups?) method returning { trainIndex, testIndex } pairs, such as TimeSeriesSplit, GroupKFold or KFold from deepbox/preprocess. Then groups is passed on to it, and shuffle and randomState are ignored.

The 4th argument is either cv (a number or a splitter) followed by scoring and an options object, or one options object holding cv, scoring, groups, shuffle and randomState.

Parameters

estimator
Estimator
Estimator with fit, predict, and score methods
X
Tensor
Features of shape (n_samples, n_features)
y
Tensor
Targets of shape (n_samples,)
cvoptional
CvSpec | CrossValScoreOptions
Number of folds, a splitter object, or an options object (default: 5)
scoringoptional
Scorer
Optional scoring function (estimator, XTest, yTest) => number used instead of estimator.score
optionsoptional
CvOptions
groups, shuffle and randomState (only with a cv that is not an options object)

Returns

number[]Array of scores, one per fold

Throws

  • InvalidParameterErrorIf cv is invalid, cv > n_samples, a splitter returns an invalid split, or the estimator has no score method and no scoring function is given
  • ShapeErrorIf X is not 2-D or X and y disagree on the number of samples
Example
import { crossValScore } from 'deepbox/ml';import { LogisticRegression } from 'deepbox/ml';import { TimeSeriesSplit } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const X = 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 = tensor([0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1], { dtype: 'int32' }); const scores = crossValScore(new LogisticRegression(), X, y, 5);console.log('Mean CV score:', scores.reduce((a,b) => a+b, 0) / scores.length); const ts = crossValScore(new LogisticRegression(), X, y, { cv: new TimeSeriesSplit({ nSplits: 4 }) });

makePipeline

function makePipeline(...estimators: Array<Estimator | Transformer>): Pipeline;

Convenience factory for creating a Pipeline with auto-generated step names.

Names are the lower-cased constructor names; repeated names get a numeric suffix (standardscaler, standardscaler_1, ...).

Parameters

estimators
Array<Estimator | Transformer>

Returns

Pipeline

Example
import { makePipeline, LogisticRegression } from 'deepbox/ml';import { StandardScaler } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const X = 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 = tensor([0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1], { dtype: 'int32' }); const pipe = makePipeline(new StandardScaler(), new LogisticRegression());pipe.fit(X, y);

Deprecated names

5

These older spellings still work in 1.x. New code should use the names above.

  • get_outputPrefer getOutput.
  • reset_outputPrefer resetOutput.
  • set_outputPrefer setOutput.
  • cross_val_scorePrefer crossValScore.
  • cross_validatePrefer crossValidate.
ml-model-selection.ts
import {  GridSearchCV,  LogisticRegression,  Pipeline,  crossValScore,  crossValidate,  permutationImportance,} from "deepbox/ml";import { tensor } from "deepbox/ndarray";import { StandardScaler } from "deepbox/preprocess"; const X = tensor([[1], [2], [3], [4], [5], [6], [7], [8]]);const y = tensor([0, 0, 1, 0, 1, 0, 1, 1]); const pipeline = new Pipeline([  ["scaler", new StandardScaler()],  ["model", new LogisticRegression()],]); console.log(crossValScore(pipeline, X, y, 4));console.log(crossValidate(pipeline, X, y, { cv: 4 }).testScores); const search = new GridSearchCV(new LogisticRegression(), { C: [0.1, 1, 10] }, { cv: 4 }).fit(X, y);console.log(search.bestParams, search.bestScore);const importance = permutationImportance(new LogisticRegression().fit(X, y), X, y);console.log(importance.importancesMean.toString());