deepbox/ml
Pipelines & Model Selection
Pipeline, ColumnTransformer and FeatureUnion, cross-validation, grid and randomized search, multiclass wrappers, estimator tags and permutation importance.
- Workflow
Overview
Pipelinetakes[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 asscaler__withMean.crossValScore(estimator, X, y, cv, scoring?)takes the number of folds ascv, 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.crossValidatereturns{ testScores, fitTime, scoreTime }and accepts several scorers.GridSearchCV(estimator, paramGrid, { cv, scoring })andRandomizedSearchCVclone the estimator for each candidate and refit the best one on all the data. ReadbestParams,bestScore,bestEstimatorandcvResults. Keys in the grid are constructor options such asmaxIter.setOutputandgetOutputstore 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 namescross_val_scoreandcross_validatestill work.
Classifier
typeType 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
typeType 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
typeBase 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
typeMetadata 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: booleanWhether the estimator supports multi-output targets
readonly requiresPositiveX: booleanWhether the estimator requires all features to be non-negative
readonly requiresPositiveY: booleanWhether the estimator requires the target to be non-negative
readonly supportsSparse: booleanWhether the estimator supports sparse input
readonly supportsSampleWeight: booleanWhether the estimator supports sample weights
readonly hasPredictProba: booleanWhether the estimator has a predict_proba method
readonly hasDecisionFunction: booleanWhether the estimator has a decision_function method
readonly requiresY: booleanWhether fit requires y (false for unsupervised)
OutlierDetector
typeType 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
typeOutput 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
typeType 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
typeType 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
typeOptions for permutationImportance.
readonly nRepeats?: numberNumber of shuffles per feature (default: 5).
readonly randomState?: numberSeed for the shuffles.
readonly scoring?: (estimator: Scorable, X: Tensor, y: Tensor) => numberCustom score function where larger is better (default:
estimator.score(X, y)).
PermutationImportanceResult
typeResult 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: TensorMean importance for each feature (shape: [n_features]).
readonly importancesStd: TensorStandard deviation of the importance for each feature, with ddof = 0 (shape: [n_features]).
readonly importances: TensorRaw importances matrix (shape: [n_repeats, n_features]).
CrossValidateResult
typeResult 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
typeAnything 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
typeOptions object accepted as the 4th argument of cross_val_score.
type CrossValScoreOptions = CvOptions & { cv?: CvSpec; scoring?: Scorer;};CvGroups
typeGroup label per sample, as a 1-D tensor or an array.
type CvGroups = Tensor | readonly (string | number | bigint)[];CvOptions
typeOptions shared by the cross-validation helpers.
groups?: CvGroups | undefinedGroup label per sample, forwarded to a splitter that uses groups (ignored for integer
cv).shuffle?: boolean | undefinedFor integer
cv: shuffle the samples before building folds (default: true).randomState?: number | undefinedFor integer
cvwithshuffle: seed of the shuffle (default: 0).
CvSpec
typeCross-validation strategy: a number of folds, or a splitter object.
type CvSpec = number | CrossValidator;CvSplit
typeOne train/test split, as index lists into the rows of X.
readonly trainIndex: ArrayLike<number>readonly testIndex: ArrayLike<number>
GridSearchResult
typeResult of a single parameter combination evaluation
readonly params: Record<string, unknown>readonly meanScore: numberreadonly scores: number[]
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.
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: numberBest mean CV score
bestEstimator: Estimator | undefinedBest fitted estimator, refitted on all of the data
cvResults: GridSearchResult[]All CV results, in the order the combinations were evaluated
bestIndex: numberIndex of the best combination in
cvResults(-1 before fitting)fit(X: Tensor, y: Tensor, groups?: CvGroups): thisCross-validate every combination and refit the best one.
predict(X: Tensor): TensorpredictProba(X: Tensor): TensorClass probabilities of the best estimator.
score(X: Tensor, y: Tensor): numbergetParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate 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.
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: numberBest mean CV score
bestEstimator: Estimator | undefinedBest fitted estimator, refitted on all of the data
cvResults: GridSearchResult[]CV results of the sampled combinations, in sampling order
bestIndex: numberIndex of the best combination in
cvResults(-1 before fitting)fit(X: Tensor, y: Tensor, groups?: CvGroups): thisCross-validate the sampled combinations and refit the best one.
predict(X: Tensor): TensorpredictProba(X: Tensor): TensorClass probabilities of the best estimator.
score(X: Tensor, y: Tensor): numbergetParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate 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.
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: TensorSorted class labels seen during
fit.fit(X: Tensor, y: Tensor): thisFit one binary classifier for every pair of classes.
predict(X: Tensor): TensorPredict class labels by majority vote of the pairwise classifiers.
decisionFunction(X: Tensor): TensorVote counts plus a small confidence-based tie-breaker, one column per class.
predictProba(X: Tensor): TensorEstimate class probabilities using normalized vote counts.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data and labels.
getParams(): Record<string, unknown>Parameters of this estimator: the template
estimator.setParams(params: Record<string, unknown>): thisReplace the template estimator.
clone(): OneVsOneClassifierCreate 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).
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: TensorSorted class labels seen during
fit.fit(X: Tensor, y: Tensor): thisFit one binary classifier per class.
predict(X: Tensor): TensorPredict class labels.
decisionFunction(X: Tensor): TensorConfidence score of every class, one column per class.
predictProba(X: Tensor): TensorEstimate class probabilities.
score(X: Tensor, y: Tensor): numberMean accuracy on the given data and labels.
getParams(): Record<string, unknown>Parameters of this estimator: the template
estimator.setParams(params: Record<string, unknown>): thisReplace the template estimator.
clone(): OneVsRestClassifierCreate 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.
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): thisFit every transformer on its column subset.
transform(X: Tensor): TensorTransform
Xcolumn group by column group and concatenate the results.fitTransform(X: Tensor, y?: Tensor): TensorFit 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>): thisSet
remainder, replace a spec's transformer with "passthrough" or "drop", or set transformer parameters with{ name: { param: value } }or{ name__param: value }.clone(): ColumnTransformerCreate 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.
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): thisFit every transformer on
X.transform(X: Tensor): TensorTransform
Xwith every transformer and concatenate the outputs column-wise.fitTransform(X: Tensor, y?: Tensor): TensorFit every transformer and return the concatenated outputs.
getParams(): Record<string, unknown>Parameters of every transformer, keyed by transformer name.
setParams(params: Record<string, unknown>): thisSet transformer parameters with
{ name: { param: value } }or{ name__param: value }.clone(): FeatureUnionCreate 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.
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 | undefinedClass labels of the final step, or
undefinedif it does not expose any.fit(X: Tensor, y?: Tensor): thisFit all steps.
transform(X: Tensor): TensorTransform data through all steps (final step must be a transformer).
fitTransform(X: Tensor, y?: Tensor): TensorFit and transform (final step must be a transformer).
fitPredict(X: Tensor, y?: Tensor): TensorFit the pipeline and return the final step's predictions for
X.predict(X: Tensor): TensorTransform data through intermediate steps, then predict with final step.
predictProba(X: Tensor): TensorTransform data through intermediate steps, then predict probabilities.
decisionFunction(X: Tensor): TensorTransform data through intermediate steps, then compute the final step's decision function.
score(X: Tensor, y: Tensor): numberTransform data through intermediate steps, then score with final step.
inverseTransform(X: Tensor): TensorMap transformed data back to the original feature space, undoing the steps in reverse order.
getStep(name: string): Estimator | TransformerGet a named step by name.
getParams(): Record<string, unknown>Parameters of every step, keyed by step name.
setParams(params: Record<string, unknown>): thisSet step parameters.
clone(): PipelineCreate a fresh, unfitted clone of this pipeline with freshly cloned steps.
assertEstimator
function assertEstimator<T extends Estimator>(value: T): T;Runtime helper to validate estimator-like objects.
Parameters
valueT- Candidate estimator
Returns
Tvalue unchanged, typed as an estimator
Throws
InvalidParameterErrorIfvalueis not an object or lacksfit,getParamsorsetParams
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
estimatorEstimator- 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
outputTypeOutputType- "default" for Tensor, "array" for plain nested number arrays
Throws
InvalidParameterErrorIfoutputTypeis not "default" or "array"
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
estimatorScorable- A fitted estimator with a
score(X, y)method XTensor- Test features of shape (n_samples, n_features)
yTensor- Test labels/targets of shape (n_samples,)
optionsoptionalPermutationImportanceOptions- Configuration options
Returns
PermutationImportanceResultPermutation importance result
Throws
ShapeErrorIfXis not 2-D,yis not 1-D, or their sample counts differDataValidationErrorIfXhas no samples or no featuresInvalidParameterErrorIfnRepeatsis not an integer >= 1, orestimatorhas noscoremethod and noscoringfunction is given
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
estimatorEstimator- Estimator with
fitandscoremethods XTensor- Features of shape (n_samples, n_features)
yTensor- Targets of shape (n_samples,)
optionsoptionalCvOptions & { 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
InvalidParameterErrorIfcvis invalid,scoringis empty or holds a non-function, or no scorer is available
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
estimatorEstimator- Estimator with
fit,predict, andscoremethods XTensor- Features of shape (n_samples, n_features)
yTensor- Targets of shape (n_samples,)
cvoptionalCvSpec | CrossValScoreOptions- Number of folds, a splitter object, or an options object (default: 5)
scoringoptionalScorer- Optional scoring function
(estimator, XTest, yTest) => numberused instead ofestimator.score optionsoptionalCvOptionsgroups,shuffleandrandomState(only with acvthat is not an options object)
Returns
number[]Array of scores, one per fold
Throws
InvalidParameterErrorIfcvis invalid,cv > n_samples, a splitter returns an invalid split, or the estimator has noscoremethod and noscoringfunction is givenShapeErrorIf X is not 2-D or X and y disagree on the number of samples
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
estimatorsArray<Estimator | Transformer>
Returns
Pipeline
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);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.
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());Found a mistake? Open an issue.