deepbox/preprocess
Imputation & Feature Engineering
Imputers, discretizers, polynomial and spline features, and feature selection.
- Feature engineering
Overview
SimpleImputer(defaultstrategy: "mean") andKNNImputerfill missing values, which are NaN by default.KNNImputerfollows scikit-learn: it measures NaN-aware Euclidean distance, averages the nearest donor rows and returnsfloat64.MissingIndicatormarks where values were missing.KBinsDiscretizerdefaults tonBins: 5,strategy: "quantile"and ordinal output. A value on an inner bin edge goes to the upper bin, and a constant feature gets a single bin.PolynomialFeaturesdefaults todegree: 2and includes the bias column (includeBias: true).SelectKBestdefaults tok: 10withscoreFunc: fClassif, so it throws when the data has fewer than 10 features unless you passk.fClassif,fRegression,mutualInfoClassifandmutualInfoRegressionreturn one score per feature.RFEandRFECVrank features by a model's importances or coefficients, andSelectFromModelkeeps features above a threshold.
ImportanceEstimator
interfaceEstimator interface expected by SelectFromModel, RFE and RFECV.
After fit(X, y) the estimator must expose one of: - coef / coef_: a Tensor, typed array or array of shape [n_features] or [n_targets, n_features] (linear and SVM models) - featureImportances / featureImportances_: values of shape [n_features] (tree-based models)
fit(X: Tensor, y: Tensor): unknown
RFECVScoring
typeScoring used by RFECV: a built-in name (higher is better) or a function (yTrue, yPred) => score where higher is better.
type RFECVScoring = "accuracy" | "r2" | "neg_mean_squared_error" | "neg_mean_absolute_error" | ((yTrue: Tensor, yPred: Tensor) => number);ScoreFunc
typeScoring function type for SelectKBest. Returns one score per feature.
type ScoreFunc = (X: Tensor, y: Tensor) => number[];ScoringEstimator
interfaceEstimator with a predict method, required by RFECV for scoring.
predict(X: Tensor): Tensor
MutualInfoOptions
typeOptions shared by mutual_info_classif and mutual_info_regression.
nNeighbors?: numberNumber of neighbors used by the estimator (default 3).
randomState?: numberSeed of the small noise added to continuous variables to break ties (default 0).
discreteFeatures?: boolean | readonly boolean[] | readonly number[]Which features are discrete:
truefor all,falsefor none (default), a boolean mask with one entry per feature, or an array of feature indices.
SplineExtrapolation
typeHow transform treats values outside the range of the fitted knots.
- "constant": values are clamped to the boundary (the basis is constant outside) - "linear": the basis is continued linearly, matching the value and slope at the boundary - "continue": the boundary polynomial pieces are continued unchanged - "periodic": the input is wrapped around the fitted range - "error": out-of-range values throw a DataValidationError
type SplineExtrapolation = "constant" | "linear" | "continue" | "periodic" | "error";SplineKnots
typeHow the knots are placed along each feature.
- "quantile": at evenly spaced quantiles of the training data - "uniform": evenly spaced between the training minimum and maximum
type SplineKnots = "quantile" | "uniform";KBinsDiscretizer
Bin continuous data into intervals.
Supports uniform (equal-width) and quantile (equal-frequency) strategies. A value that falls exactly on an inner bin edge goes to the upper bin, and values outside the fitted range are clipped into the first or last bin (as in scikit-learn). A constant feature gets a single bin with edges [-Infinity, Infinity], and quantile bins that collapse to zero width are merged, so a feature can end up with fewer bins than requested.
import { KBinsDiscretizer } from "deepbox/preprocess";import { tensor } from "deepbox/ndarray"; const X = tensor([[0], [1], [2], [3], [4]]);const kbd = new KBinsDiscretizer({ nBins: 2, strategy: "uniform" });kbd.fitTransform(X); // [[0], [0], [1], [1], [1]]kbd.binEdges; // [[0, 2, 4]]Members (10)
constructor(options?: { nBins?: number | readonly number[]; strategy?: Strategy; encode?: Encode; })binEdges: number[][]Learned bin edges, one ascending array per feature (a copy).
nBinsPerFeature: number[]Number of bins actually used per feature after fitting.
fit(X: Tensor): thisLearn the bin edges of every feature.
transform(X: Tensor): TensorReplace every value by the index of its bin (or by a one-hot block when
encodeis "onehot-dense").fitTransform(X: Tensor): TensorFit to X and return its binned representation.
getParams(): Record<string, unknown>Constructor options of this discretizer.
setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): KBinsDiscretizerCreate an unfitted discretizer with the same parameters.
inverseTransform(Xt: Tensor): TensorMap bin indices (or one-hot blocks) back to the center of each bin.
RFE
Recursive Feature Elimination (RFE).
Recursively removes the least important features, re-fitting the estimator each time, until the desired number of features is reached. Importances are read as described for SelectFromModel; for multi-target coefficients the sum of squares over targets is ranked, as in scikit-learn. The estimator is cloned when possible, so the instance passed in is left untouched.
ranking is 1 for selected features. Features removed in the first round get the largest rank, features removed in the last round get 2.
import { RFE } from 'deepbox/preprocess';import { LogisticRegression } 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 rfe = new RFE({ estimator: new LogisticRegression(), nFeaturesToSelect: 3,});rfe.fit(X, y);const Xt = rfe.transform(X);Members (14)
constructor(options: { estimator: ImportanceEstimator; nFeaturesToSelect?: number; step?: number; })ranking: number[]Feature ranking (1 = selected, larger = eliminated earlier).
nFeatures: numberNumber of selected features.
fit(X: Tensor, y: Tensor): thisEliminate features recursively until
nFeaturesToSelectremain.transform(X: Tensor): TensorKeep only the selected features.
fitTransform(X: Tensor, y: Tensor): TensorinverseTransform(X: Tensor): TensorMap reduced data back to the original features; dropped features become zeros.
getSupport(): boolean[]Selection mask (true = kept), or the kept indices when
indicesis true.getSupport(indices: false): boolean[]getSupport(indices: true): number[]getSupport(indices?: boolean): boolean[] | number[]getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): RFECreate an unfitted copy; the inner estimator is cloned as well.
RFECV
Recursive Feature Elimination with Cross-Validation (RFECV).
Runs RFE inside each cross-validation fold. On every fold the estimator is fitted on the training part with the currently active features, scored on the validation part, and then used to drop the least important features. The feature count with the best mean score is chosen (the smallest count on ties) and RFE is run once more on all data to pick the final features.
Scoring: scoring if given. Otherwise the estimator's own score(X, y) is used when it exists (accuracy for classifiers, R^2 for regressors), and accuracy computed from predict when it does not. Folds are stratified for classifiers with accuracy scoring (see stratified); otherwise they are contiguous blocks, so shuffle ordered data beforehand.
import { RFECV } from 'deepbox/preprocess';import { LogisticRegression } 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 rfecv = new RFECV({ estimator: new LogisticRegression(), cv: 5, step: 1,});rfecv.fit(X, y);console.log(rfecv.nFeatures); // optimal number of featuresconst Xt = rfecv.transform(X);Members (16)
constructor(options: { estimator: ScoringEstimator; cv?: number; step?: number; minFeaturesToSelect?: number; scoring?: RFECVScoring; stratified?: boolean; })ranking: number[]Feature ranking (1 = selected, larger = eliminated earlier).
nFeatures: numberOptimal number of features selected by cross-validation.
gridScores: Map<number, number>Mean cross-validation score for each feature count tested (most features first).
gridScoresStd: Map<number, number>Standard deviation of the cross-validation scores for each feature count tested.
fit(X: Tensor, y: Tensor): thisChoose the number of features by cross-validation, then select them.
transform(X: Tensor): TensorKeep only the selected features.
fitTransform(X: Tensor, y: Tensor): TensorinverseTransform(X: Tensor): TensorMap reduced data back to the original features; dropped features become zeros.
getSupport(): boolean[]Selection mask (true = kept), or the kept indices when
indicesis true.getSupport(indices: false): boolean[]getSupport(indices: true): number[]getSupport(indices?: boolean): boolean[] | number[]getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): RFECVCreate an unfitted copy; the inner estimator is cloned as well.
SelectFromModel
Meta-transformer for selecting features based on importance weights from a fitted estimator.
The estimator is cloned and fitted on the data; the user's instance is not modified when it can be cloned (it has clone() or a getParams() that its constructor accepts). The fitted copy is available as fittedEstimator.
Importances come from coef/coef_ (absolute values; for multi-target coefficients the sum of absolute values over targets, like scikit-learn) or from featureImportances/featureImportances_. A feature is kept when its importance is greater than or equal to the threshold, and at most maxFeatures features with the largest importances are kept.
import { SelectFromModel } from 'deepbox/preprocess';import { RandomForestClassifier } 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 selector = new SelectFromModel({ estimator: new RandomForestClassifier(), threshold: 'mean',});selector.fit(X, y);const Xt = selector.transform(X);Members (15)
constructor(options: { estimator: ImportanceEstimator; threshold?: "mean" | "median" | number; maxFeatures?: number; })importances: number[]Importances read from the estimator during fit.
fittedEstimator: ImportanceEstimatorThe estimator instance that was fitted (a clone of the one passed in, when clonable).
nFeaturesIn: numberNumber of features seen during fit.
fit(X: Tensor, y: Tensor): thisFit the estimator and select features by importance.
transform(X: Tensor): TensorKeep only the selected features.
fitTransform(X: Tensor, y: Tensor): TensorinverseTransform(X: Tensor): TensorMap reduced data back to the original features; dropped features become zeros.
getSupport(): boolean[]Selection mask (true = kept), or the kept indices when
indicesis true.getSupport(indices: false): boolean[]getSupport(indices: true): number[]getSupport(indices?: boolean): boolean[] | number[]getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): SelectFromModelCreate an unfitted copy; the inner estimator is cloned as well.
SelectKBest
Select features according to the k highest scores.
Features with NaN scores rank last. Among equal scores the feature with the lowest index is kept first. transform keeps the dtype of the input.
import { SelectKBest, fClassif } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]);const y = tensor([0,0,1,1]);const skb = new SelectKBest({ scoreFunc: fClassif, k: 2 });skb.fit(X, y);const Xt = skb.transform(X);Members (14)
constructor(options?: { scoreFunc?: ScoreFunc; k?: number | "all"; })scores: number[]Feature scores computed during fit (NaN scores are kept as returned).
nFeaturesIn: numberNumber of features seen during fit.
fit(X: Tensor, y: Tensor): thisScore every feature and select the k best.
transform(X: Tensor): TensorKeep only the selected features.
fitTransform(X: Tensor, y: Tensor): TensorinverseTransform(X: Tensor): TensorMap reduced data back to the original features; dropped features become zeros.
getSupport(): boolean[]Selection mask (true = kept), or the kept indices when
indicesis true.getSupport(indices: false): boolean[]getSupport(indices: true): number[]getSupport(indices?: boolean): boolean[] | number[]getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): SelectKBestCreate an unfitted copy with the same parameters.
VarianceThreshold
Feature selector that removes all low-variance features.
Features with a variance lower than or equal to the threshold are removed. By default only zero-variance (constant) features are removed. Variances are the population variances (divisor n), computed with NaN values ignored. Constant columns always get a variance of exactly 0, so the default threshold is not defeated by rounding error in the column mean.
transform keeps the dtype of the input.
import { VarianceThreshold } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const X = tensor([[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1]]);const selector = new VarianceThreshold({ threshold: 0.0 });selector.fit(X);const Xt = selector.transform(X); // removes constant columnsMembers (14)
constructor(options?: { threshold?: number; })variances: number[]Per-feature variances (NaN ignored; NaN for an all-NaN column).
nFeaturesIn: numberNumber of features seen during fit.
fit(X: Tensor, _y?: Tensor): thisLearn the per-feature variances.
transform(X: Tensor): TensorKeep only the features whose variance exceeds the threshold.
fitTransform(X: Tensor, y?: Tensor): TensorinverseTransform(X: Tensor): TensorMap reduced data back to the original number of features.
getSupport(): boolean[]Get the selection mask (true = kept), or the indices of the kept features when
indicesis true.getSupport(indices: false): boolean[]getSupport(indices: true): number[]getSupport(indices?: boolean): boolean[] | number[]getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): VarianceThresholdCreate an unfitted copy with the same parameters.
KNNImputer
KNN-based imputation for completing missing values.
Follows sklearn.impute.KNNImputer. For every row with missing values, the distance to each training row is the NaN-aware Euclidean distance sqrt(n_features / n_shared * sum((a - b)^2)) over the features present in both rows. Each missing value is then the mean of that feature over the nNeighbors nearest training rows that have the feature observed (a distance-weighted mean for weights: 'distance'; if a donor is at distance 0 only the donors at distance 0 are used). When no donor exists, the training column mean is used (0 if the column has no observed value). The output is float32 for float32 input and float64 otherwise.
import { KNNImputer } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const imp = new KNNImputer({ nNeighbors: 3 });const X = tensor([[1, 2], [NaN, 3], [7, NaN], [4, 5]]);const filled = imp.fitTransform(X);Members (7)
constructor(options?: { readonly nNeighbors?: number; readonly weights?: "uniform" | "distance"; readonly missingValues?: number; readonly keepEmptyFeatures?: boolean; })fit(X: Tensor): thisStore the training data used to find neighbors.
transform(X: Tensor): TensorImpute the missing values of X from the training data.
fitTransform(X: Tensor): TensorgetParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): KNNImputerCreate an unfitted copy with the same parameters.
MissingIndicator
Binary indicator for missing values.
Generates a matrix where 1 marks a missing value (NaN, or the value given by missingValues) and 0 a present value, as float64. Useful as an additional feature set to complement imputation.
With features: 'missing-only' (the default) only columns that had missing values during fit are output. If errorOnNew is true (the default, as in scikit-learn), transform throws when another column contains missing values, because the indicator would silently ignore them.
import { MissingIndicator } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const mi = new MissingIndicator();const X = tensor([[1, NaN], [NaN, 3], [7, 6]]);mi.fit(X);const indicators = mi.transform(X);// indicators shape: [3, 2], values: [[0, 1], [1, 0], [0, 0]]Members (8)
constructor(options?: { readonly features?: "missing-only" | "all"; readonly missingValues?: number; readonly errorOnNew?: boolean; })features_: number[]Get the indices of the features that produce an indicator column.
fit(X: Tensor): thisFind the columns that contain missing values.
transform(X: Tensor): TensorBuild the indicator matrix.
fitTransform(X: Tensor): TensorgetParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): MissingIndicatorCreate an unfitted copy with the same parameters.
SimpleImputer
Simple imputation transformer for completing missing values.
Replaces missing values (NaN, or the value given by missingValues) using a statistic of each feature column (mean, median, most frequent value) or a constant. The statistics ignore missing entries. For most_frequent, ties are broken towards the smallest value. The output is float32 for float32 input and float64 otherwise.
A column without any observed value gets 0 for mean, median and most_frequent when keepEmptyFeatures is true (the default), and is dropped from the output when it is false (its statistic is then NaN).
import { SimpleImputer } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const imp = new SimpleImputer({ strategy: 'mean' });const X = tensor([[1, 2], [NaN, 3], [7, NaN]]);imp.fit(X);const X_filled = imp.transform(X);Members (8)
constructor(options?: { readonly strategy?: ImputeStrategy; readonly fillValue?: number; readonly missingValues?: number; readonly keepEmptyFeatures?: boolean; })statistics: number[]Get the computed imputation statistics per feature (NaN for a dropped column).
fit(X: Tensor): thisCompute the imputation statistics from training data.
transform(X: Tensor): TensorImpute missing values in X using the fitted statistics.
fitTransform(X: Tensor): TensorFit and transform in one step.
getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): SimpleImputerCreate an unfitted copy with the same parameters.
Binarizer
Binarize data (set feature values to 0 or 1) according to a threshold.
Values greater than the threshold map to 1, while values less than or equal to the threshold (and NaN) map to 0. The output is float32 for float32 input and float64 otherwise.
import { Binarizer } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const binarizer = new Binarizer({ threshold: 1.5 });const X = tensor([[1, 2], [3, 0.5]]);const Xb = binarizer.fitTransform(X);// Xb = [[0, 1], [1, 0]]Members (7)
constructor(options?: { readonly threshold?: number; })fit(X: Tensor): thisRecord the number of input features (the transformer is otherwise stateless).
transform(X: Tensor): TensorBinarize X.
fitTransform(X: Tensor): TensorgetParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): BinarizerCreate an unfitted copy with the same parameters.
FunctionTransformer
Constructs a transformer from an arbitrary callable.
Useful for wrapping arbitrary functions in a Pipeline-compatible transformer without subclassing. With no func the transform is the identity and returns the input tensor itself. inverseTransform applies inverseFunc, or is the identity when there is none; it does not require fit.
import { FunctionTransformer } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const log1p = new FunctionTransformer({ func: (X) => { // apply log1p element-wise const data = []; for (let i = 0; i < X.size; i++) data.push(Math.log1p(Number(X.data[X.offset + i]))); return tensor(data).reshape(X.shape); },});Members (8)
constructor(options?: { readonly func?: (X: Tensor) => Tensor; readonly inverseFunc?: (X: Tensor) => Tensor; })fit(_X: Tensor): thistransform(X: Tensor): TensorApply
functo X.fitTransform(X: Tensor): TensorinverseTransform(X: Tensor): TensorApply
inverseFuncto X (identity when none was given).getParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): FunctionTransformerCreate an unfitted copy with the same parameters.
PolynomialFeatures
Generate polynomial and interaction features.
Generates a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree. The column order matches scikit-learn: by degree, and within a degree in lexicographic order of the feature indices.
For example, if input has features [a, b] and degree=2: - interactionOnly=false: [1, a, b, a², ab, b²] - interactionOnly=true: [1, a, b, ab]
The output is float32 for float32 input and float64 otherwise. The number of output columns grows quickly with the degree and the number of features; very large requests throw a MemoryError instead of exhausting memory.
import { PolynomialFeatures } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const poly = new PolynomialFeatures({ degree: 2 });const X = tensor([[1, 2], [3, 4]]);const Xpoly = poly.fitTransform(X);// Xpoly has columns: [1, x1, x2, x1², x1*x2, x2²]Members (10)
constructor(options?: { readonly degree?: number; readonly interactionOnly?: boolean; readonly includeBias?: boolean; })nOutputFeatures: numberNumber of output features after transformation
powers: number[][]Exponent of each input feature in each output column, shape
[n_output_features][n_input_features].fit(X: Tensor): thisRecord the number of input features.
transform(X: Tensor): TensorExpand X into polynomial features.
fitTransform(X: Tensor): TensorgetParams(): Record<string, unknown>setParams(params: Record<string, unknown>): thisUpdate parameters.
clone(): PolynomialFeaturesCreate an unfitted copy with the same parameters.
getFeatureNamesOut(inputFeatures?: readonly string[]): string[]Names of the output columns, in the same format as scikit-learn (
1,x0,x0^2,x0 x1).
SplineTransformer
Generate B-spline basis features for each input feature.
Transforms each feature into a set of B-spline basis functions, which can capture nonlinear relationships while remaining linear in the parameters (useful for linear models).
With nKnots knots and spline degree degree every feature produces nKnots + degree - 1 basis columns (nKnots - 1 for periodic splines), one fewer when includeBias is false. Columns are grouped by input feature. The knot vector is clamped (boundary knots repeated degree extra times), so the basis is the textbook B-spline basis; it spans the same functions as scikit-learn's, but individual columns differ from scikit-learn's. A feature with a single distinct value in the training data has no knot span and gives all-zero columns, as in scikit-learn.
import { SplineTransformer } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const st = new SplineTransformer({ nKnots: 5, degree: 3 });const X = tensor([[0], [0.25], [0.5], [0.75], [1.0]]);const Xt = st.fitTransform(X); // shape [5, 7]Members (10)
constructor(options?: SplineOptions)Creates a new SplineTransformer.
nFeaturesOut: numberNumber of output columns.
knotPositions: number[][] | undefinedKnots placed on each feature during fitting (one array of
nKnotsvalues per feature), orundefinedif unfitted.fit(X: Tensor, _y?: Tensor): thisPlace the knots on the training data of each feature.
transform(X: Tensor): TensorEvaluate the spline basis of every feature.
fitTransform(X: Tensor, _y?: Tensor): TensorFit to X, then transform it.
inverseTransform(_X: Tensor): TensorSpline features cannot be inverted, so this always throws.
getParams(): Record<string, unknown>Constructor options of this transformer.
setParams(params: Record<string, unknown>): thisChange options.
clone(): SplineTransformerCreate an unfitted transformer with the same options.
fClassif
function fClassif(X: Tensor, y: Tensor): number[];ANOVA F-value between each feature and the target classes.
Returns one F statistic per feature, MSB / MSW, where the class labels in y define the groups. Same statistic as sklearn.feature_selection.f_classif (without the p-values). Constant features and targets with a single class score 0; an exactly zero within-class variance with separated class means scores Infinity.
Parameters
XTensor- Features of shape (n_samples, n_features); must be finite
yTensor- Class labels of shape (n_samples,)
Returns
number[]F statistics, one per feature
Throws
ShapeErrorIf X is not 2D or y does not match XDataValidationErrorIf X or y contain NaN or infinity
fRegression
function fRegression(X: Tensor, y: Tensor): number[];Univariate F statistic of the linear regression of y on each feature.
For each feature the Pearson correlation r with y is turned into F = r^2 / (1 - r^2) * (n - 2), as in sklearn.feature_selection.f_regression with center=True (p-values are not returned). Constant features, a constant target and fewer than three samples score 0; a perfect correlation scores Infinity.
Parameters
XTensor- Features of shape (n_samples, n_features); must be finite
yTensor- Continuous target of shape (n_samples,)
Returns
number[]F statistics, one per feature
Throws
ShapeErrorIf X is not 2D or y does not match XDataValidationErrorIf X or y contain NaN or infinity
mutualInfoClassif
function mutualInfoClassif(X: Tensor, y: Tensor, options?: MutualInfoOptions): number[];Estimate mutual information between each feature and a discrete target variable.
Details
Mutual information (MI) measures the dependency between variables. It equals zero iff two random variables are independent, and higher values mean higher dependency. Continuous features are scaled to unit standard deviation, jittered by a tiny seeded noise to break ties, and scored with the nearest-neighbor estimator of Ross (2014), as in scikit-learn. Features listed in discreteFeatures are scored from the contingency table with the target instead. Samples whose class occurs only once are ignored by the continuous estimator.
Can be used as a scoreFunc for SelectKBest.
Parameters
XTensor- Feature matrix of shape [n_samples, n_features]; must be finite
yTensor- Target vector of shape [n_samples] (discrete class labels)
optionsoptionalMutualInfoOptions- Optional parameters
Returns
number[]Array of MI scores, one per feature (in nats, not bits)
Throws
DTypeErrorIf X or y is a string tensorDataValidationErrorIf X or y contain NaN or infinity
import { mutualInfoClassif, SelectKBest } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 2], [3, 4], [5, 6], [7, 8]]);const y = tensor([0, 0, 1, 1]);const scores = mutualInfoClassif(X, y); // Use with SelectKBestconst skb = new SelectKBest({ scoreFunc: mutualInfoClassif, k: 1 });skb.fit(X, y);mutualInfoRegression
function mutualInfoRegression(X: Tensor, y: Tensor, options?: MutualInfoOptions): number[];Estimate mutual information between each feature and a continuous target variable.
Details
Mutual information (MI) measures the dependency between variables. It equals zero iff two random variables are independent, and higher values mean higher dependency. Continuous features and the target are scaled to unit standard deviation (the joint nearest-neighbor search uses the Chebyshev distance, so the scale matters), jittered by a tiny seeded noise, and scored with the KSG estimator, as in scikit-learn. Features listed in discreteFeatures are scored against the target with the continuous-discrete estimator.
Can be used as a scoreFunc for SelectKBest.
Parameters
XTensor- Feature matrix of shape [n_samples, n_features]; must be finite
yTensor- Target vector of shape [n_samples] (continuous values)
optionsoptionalMutualInfoOptions- Optional parameters
Returns
number[]Array of MI scores, one per feature (in nats, not bits)
Throws
DTypeErrorIf X or y is a string tensorDataValidationErrorIf X or y contain NaN or infinity
import { mutualInfoRegression, SelectKBest } from 'deepbox/preprocess';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 0.5], [2, 1.5], [3, 2.5], [4, 3.5]]);const y = tensor([1.1, 2.1, 3.1, 4.1]);const scores = mutualInfoRegression(X, y); // Use with SelectKBestconst skb = new SelectKBest({ scoreFunc: mutualInfoRegression, k: 1 });skb.fit(X, y);These older spellings still work in 1.x. New code should use the names above.
f_classifPrefer fClassif.f_regressionPrefer fRegression.mutual_info_classifPrefer mutualInfoClassif.mutual_info_regressionPrefer mutualInfoRegression.
import { KBinsDiscretizer, KNNImputer, PolynomialFeatures, SelectKBest, SimpleImputer, VarianceThreshold,} from "deepbox/preprocess";import { tensor } from "deepbox/ndarray"; const X = tensor([[1, 2], [1, 3], [2, 5], [4, 8]]);const withGaps = tensor([[1, Number.NaN], [2, 3], [4, 5]]); console.log(new SimpleImputer({ strategy: "median" }).fitTransform(withGaps).toString());console.log(new KNNImputer({ nNeighbors: 2 }).fitTransform(withGaps).toString());console.log(new PolynomialFeatures({ degree: 2 }).fitTransform(X).toString());console.log(new KBinsDiscretizer({ nBins: 3 }).fitTransform(X).toString());console.log(new VarianceThreshold().fitTransform(X).toString());console.log(new SelectKBest({ k: 1 }).fit(X, tensor([0, 0, 1, 1])).transform(X).toString());Found a mistake? Open an issue.