deepbox/ml
Decomposition
PCA, truncated SVD, NMF, FastICA and latent Dirichlet allocation.
- Dimensionality reduction
Overview
PCAkeepsmin(nSamples, nFeatures)components unless you setnComponents. It centers the data but does not scale it, so standardize first when features use different units. Readcomponents,explainedVariance,explainedVarianceRatio,singularValuesandmeanfrom the fitted model.TruncatedSVDdoes not center the data.NMFneeds non-negative input and starts from random values by default (init: "nndsvd"is available).FastICAwhitens by default and uses thelogcoshcontrast function.LatentDirichletAllocationexpects a matrix of word counts and defaults to 10 topics.- Pass
randomStatefor repeatable results where an algorithm starts from random values.
FastICA
FastICA: Independent Component Analysis using the fast fixed-point algorithm.
Separates a multivariate signal into additive, independent non-Gaussian components. Uses negentropy maximization with the logcosh or exp contrast functions (or the kurtosis-based cube function), symmetric decorrelation (parallel algorithm) and, by default, whitening to unit variance.
After fitting, components holds the unmixing matrix W·K of shape (n_components, n_features) so that transform(X) = (X - mean) @ componentsᵀ, and mixingMatrix is its pseudo-inverse of shape (n_features, n_components). Independent components are only defined up to sign, scale and order.
import { FastICA } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 5], [3, 1], [5, 4], [7, 3], [9, 8], [2, 6]]);const ica = new FastICA({ nComponents: 2, randomState: 0 });const S = ica.fitTransform(X);Members (12)
constructor(options?: { readonly nComponents?: number; readonly maxIter?: number; readonly tol?: number; readonly fun?: IcaFun; readonly whiten?: boolean; readonly randomState?: number; })components: TensorUnmixing matrix in feature space, shape (n_components, n_features).
mixingMatrix: TensorMixing matrix (pseudo-inverse of
components), shape (n_features, n_components).mean: TensorPer-feature mean of the training data, shape (n_features,).
nIter: numberNumber of fixed-point iterations run by the last fit.
nFeaturesIn: numberNumber of features seen during fit.
fit(X: Tensor, _y?: Tensor): thisFit the model: estimate the unmixing matrix.
transform(X: Tensor): TensorRecover the sources:
(X - mean) @ componentsᵀ.fitTransform(X: Tensor, _y?: Tensor): TensorFit the model and return the recovered sources.
inverseTransform(X: Tensor): TensorMap sources back to the feature space:
S @ mixingMatrixᵀ + mean.getParams(): Record<string, unknown>Get hyperparameters for this estimator.
setParams(params: Record<string, unknown>): thisSet the parameters of this estimator.
LatentDirichletAllocation
Latent Dirichlet Allocation (LDA) for topic modeling.
Decomposes a document-term matrix into document-topic and topic-term distributions using batch variational Bayes inference. This is the topic model, not Linear Discriminant Analysis (see LinearDiscriminantAnalysis).
Input X should be a non-negative matrix (e.g., from CountVectorizer).
import { LatentDirichletAllocation } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[3, 0, 1], [0, 2, 4], [1, 1, 1]]);const lda = new LatentDirichletAllocation({ nComponents: 2, randomState: 0 });const docTopics = lda.fitTransform(X);Members (10)
constructor(options?: { readonly nComponents?: number; readonly maxIter?: number; readonly tol?: number; readonly docTopicPrior?: number; readonly topicWordPrior?: number; readonly randomState?: number; })components: TensorTopic-word variational parameters (lambda), shape (n_components, n_features).
nIter: numberNumber of passes over the corpus run by the last fit.
nFeaturesIn: numberNumber of features (vocabulary size) seen during fit.
fit(X: Tensor, _y?: Tensor): thisFit the topic model with batch variational Bayes.
transform(X: Tensor): TensorInfer normalized document-topic distributions for X.
fitTransform(X: Tensor, _y?: Tensor): TensorFit the model and return the document-topic distributions of X.
inverseTransform(X: Tensor): TensorTransform topic distributions back to approximate word distributions.
getParams(): Record<string, unknown>Get hyperparameters for this estimator.
setParams(params: Record<string, unknown>): thisSet the parameters of this estimator.
NMF
Non-negative Matrix Factorization (NMF).
Factorizes a non-negative matrix X ≈ W * H where: - W is the transformed data (n_samples × n_components) - H is the components matrix (n_components × n_features) - Both W and H are non-negative
Uses multiplicative update rules (Lee & Seung, 2001) that minimize the squared Frobenius norm. With init: "random" the factors start from non-negative random values scaled to the data (sqrt(mean(X) / nComponents)); "nndsvd" and "nndsvda" use a deterministic SVD-based start (Boutsidis & Gallopoulos, 2008). Plain "nndsvd" produces exact zeros, which multiplicative updates never change, so "nndsvda" is usually the better choice.
Useful for topic modeling, recommendation systems, and signal separation.
import { NMF } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 0, 2], [0, 3, 1], [2, 1, 0], [1, 2, 3]]);const nmf = new NMF({ nComponents: 2, randomState: 0 });const W = nmf.fitTransform(X); // X must be non-negativeMembers (11)
constructor(options?: { readonly nComponents?: number; readonly maxIter?: number; readonly tol?: number; readonly randomState?: number; readonly init?: NmfInit; })components: TensorFactorization matrix H, shape (n_components, n_features).
nIter: numberNumber of iterations run by the last fit.
reconstructionErr: numberFrobenius norm of X - W @ H for the training data of the last fit.
nFeaturesIn: numberNumber of features seen during fit.
fit(X: Tensor, _y?: Tensor): thisFit the model to a non-negative matrix.
transform(X: Tensor): TensorCompute W for new data with H held fixed.
fitTransform(X: Tensor, _y?: Tensor): TensorFit the model and return W from the fit.
inverseTransform(X: Tensor): TensorReconstruct data as W @ H.
getParams(): Record<string, unknown>Get hyperparameters for this estimator.
setParams(params: Record<string, unknown>): thisSet the parameters of this estimator.
PCA
Principal Component Analysis (PCA).
Linear dimensionality reduction using Singular Value Decomposition (SVD) to project data to a lower dimensional space.
Algorithm: 1. Center the data by subtracting the column means 2. Compute SVD: X = U * Σ * V^T (exact, or randomized with power iterations) 3. Principal components are the rows of V^T, signed so that the entry of largest magnitude in each component is positive (same convention as scikit-learn) 4. Transform data by projecting onto the principal components
Time Complexity: O(min(n*d^2, d*n^2)) for the exact solver, where n=samples, d=features
import { PCA } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[2.5, 2.4], [0.5, 0.7], [2.2, 2.9], [1.9, 2.2], [3.1, 3.0]]);const pca = new PCA({ nComponents: 1 });pca.fit(X); const XTransformed = pca.transform(X);console.log('Explained variance ratio:', pca.explainedVarianceRatio);Members (14)
constructor(options?: { readonly nComponents?: number; readonly whiten?: boolean; readonly svdSolver?: "auto" | "full" | "randomized"; readonly nOversamples?: number; readonly randomState?: number; })Create a new PCA model.
components: TensorPrincipal axes in feature space, shape (n_components, n_features).
explainedVariance: TensorVariance explained by each component, shape (n_components,).
explainedVarianceRatio: TensorFraction of the total variance explained by each component, shape (n_components,).
singularValues: TensorSingular values of the centered training data for the kept components, shape (n_components,).
mean: TensorPer-feature mean of the training data, shape (n_features,).
noiseVariance: numberAverage variance of the discarded components (0 when all components are kept).
nFeaturesIn: numberNumber of features seen during fit.
fit(X: Tensor, _y?: Tensor): thisFit PCA on training data.
transform(X: Tensor): TensorTransform data to principal component space.
fitTransform(X: Tensor, _y?: Tensor): TensorFit and transform in one step.
inverseTransform(X: Tensor): TensorTransform data back to original space.
getParams(): Record<string, unknown>Get hyperparameters for this estimator.
setParams(params: Record<string, unknown>): thisSet the parameters of this estimator.
TruncatedSVD
Truncated SVD (aka LSA: Latent Semantic Analysis).
Unlike PCA, TruncatedSVD does not center the data before computing SVD. This makes it suitable for sparse data (e.g., TF-IDF matrices from text), where centering would destroy sparsity.
Algorithm: 1. Compute SVD of X directly: X ≈ U * Σ * V^T (truncated to nComponents) 2. Components are rows of V^T (signed so the largest-magnitude entry is positive) 3. Transform: X_new = X @ V = U * Σ
explainedVariance is the variance of each transformed column (population variance, ddof = 0) and explainedVarianceRatio divides it by the total variance of the columns of X, as in scikit-learn.
import { TruncatedSVD } from 'deepbox/ml';import { tensor } from 'deepbox/ndarray'; const X = tensor([[1, 0, 2, 0], [0, 3, 0, 1], [4, 0, 1, 0], [0, 2, 0, 5]]);const tsvd = new TruncatedSVD({ nComponents: 2 });const XReduced = tsvd.fitTransform(X);Members (12)
constructor(options?: { readonly nComponents?: number; })components: TensorRight singular vectors, shape (n_components, n_features).
explainedVariance: TensorVariance of each transformed column (ddof = 0), shape (n_components,).
explainedVarianceRatio: TensorFraction of the total column variance of X explained by each component.
singularValues: TensorSingular values of X for the kept components, shape (n_components,).
nFeaturesIn: numberNumber of features seen during fit.
fit(X: Tensor, _y?: Tensor): thisFit the model on X.
transform(X: Tensor): TensorProject X onto the fitted right singular vectors.
fitTransform(X: Tensor, _y?: Tensor): TensorFit the model and return the reduced data.
inverseTransform(X: Tensor): TensorMap reduced data back to the original feature space.
getParams(): Record<string, unknown>Get hyperparameters for this estimator.
setParams(params: Record<string, unknown>): thisSet the parameters of this estimator.
import { FastICA, NMF, PCA, TruncatedSVD } from "deepbox/ml";import { tensor } from "deepbox/ndarray"; const X = tensor([ [1, 2, 3], [2, 3, 4.5], [3, 4, 5], [4, 5.5, 6],]); const pca = new PCA({ nComponents: 2 });console.log(pca.fitTransform(X).toString());console.log(pca.explainedVarianceRatio?.toString());console.log(new TruncatedSVD({ nComponents: 2 }).fitTransform(X).shape);console.log(new FastICA({ nComponents: 2, randomState: 0 }).fitTransform(X).shape);console.log(new NMF({ nComponents: 2, randomState: 0 }).fitTransform(X).shape);Found a mistake? Open an issue.