Skip to content

deepbox/ml

Decomposition

PCA, truncated SVD, NMF, FastICA and latent Dirichlet allocation.

  • Dimensionality reduction

Overview

  • PCA keeps min(nSamples, nFeatures) components unless you set nComponents. It centers the data but does not scale it, so standardize first when features use different units. Read components, explainedVariance, explainedVarianceRatio, singularValues and mean from the fitted model.
  • TruncatedSVD does not center the data. NMF needs non-negative input and starts from random values by default (init: "nndsvd" is available). FastICA whitens by default and uses the logcosh contrast function. LatentDirichletAllocation expects a matrix of word counts and defaults to 10 topics.
  • Pass randomState for repeatable results where an algorithm starts from random values.

Classes

5

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.

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

    Unmixing matrix in feature space, shape (n_components, n_features).

  • mixingMatrix: Tensor

    Mixing matrix (pseudo-inverse of components), shape (n_features, n_components).

  • mean: Tensor

    Per-feature mean of the training data, shape (n_features,).

  • nIter: number

    Number of fixed-point iterations run by the last fit.

  • nFeaturesIn: number

    Number of features seen during fit.

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

    Fit the model: estimate the unmixing matrix.

  • transform(X: Tensor): Tensor

    Recover the sources: (X - mean) @ componentsᵀ.

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

    Fit the model and return the recovered sources.

  • inverseTransform(X: Tensor): Tensor

    Map sources back to the feature space: S @ mixingMatrixᵀ + mean.

  • getParams(): Record<string, unknown>

    Get hyperparameters for this estimator.

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

    Set 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).

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

    Topic-word variational parameters (lambda), shape (n_components, n_features).

  • nIter: number

    Number of passes over the corpus run by the last fit.

  • nFeaturesIn: number

    Number of features (vocabulary size) seen during fit.

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

    Fit the topic model with batch variational Bayes.

  • transform(X: Tensor): Tensor

    Infer normalized document-topic distributions for X.

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

    Fit the model and return the document-topic distributions of X.

  • inverseTransform(X: Tensor): Tensor

    Transform topic distributions back to approximate word distributions.

  • getParams(): Record<string, unknown>

    Get hyperparameters for this estimator.

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

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

Example
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-negative
Members (11)
  • constructor(options?: { readonly nComponents?: number; readonly maxIter?: number; readonly tol?: number; readonly randomState?: number; readonly init?: NmfInit; })
  • components: Tensor

    Factorization matrix H, shape (n_components, n_features).

  • nIter: number

    Number of iterations run by the last fit.

  • reconstructionErr: number

    Frobenius norm of X - W @ H for the training data of the last fit.

  • nFeaturesIn: number

    Number of features seen during fit.

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

    Fit the model to a non-negative matrix.

  • transform(X: Tensor): Tensor

    Compute W for new data with H held fixed.

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

    Fit the model and return W from the fit.

  • inverseTransform(X: Tensor): Tensor

    Reconstruct data as W @ H.

  • getParams(): Record<string, unknown>

    Get hyperparameters for this estimator.

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

    Set 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

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

    Principal axes in feature space, shape (n_components, n_features).

  • explainedVariance: Tensor

    Variance explained by each component, shape (n_components,).

  • explainedVarianceRatio: Tensor

    Fraction of the total variance explained by each component, shape (n_components,).

  • singularValues: Tensor

    Singular values of the centered training data for the kept components, shape (n_components,).

  • mean: Tensor

    Per-feature mean of the training data, shape (n_features,).

  • noiseVariance: number

    Average variance of the discarded components (0 when all components are kept).

  • nFeaturesIn: number

    Number of features seen during fit.

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

    Fit PCA on training data.

  • transform(X: Tensor): Tensor

    Transform data to principal component space.

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

    Fit and transform in one step.

  • inverseTransform(X: Tensor): Tensor

    Transform data back to original space.

  • getParams(): Record<string, unknown>

    Get hyperparameters for this estimator.

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

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

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

    Right singular vectors, shape (n_components, n_features).

  • explainedVariance: Tensor

    Variance of each transformed column (ddof = 0), shape (n_components,).

  • explainedVarianceRatio: Tensor

    Fraction of the total column variance of X explained by each component.

  • singularValues: Tensor

    Singular values of X for the kept components, shape (n_components,).

  • nFeaturesIn: number

    Number of features seen during fit.

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

    Fit the model on X.

  • transform(X: Tensor): Tensor

    Project X onto the fitted right singular vectors.

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

    Fit the model and return the reduced data.

  • inverseTransform(X: Tensor): Tensor

    Map reduced data back to the original feature space.

  • getParams(): Record<string, unknown>

    Get hyperparameters for this estimator.

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

    Set the parameters of this estimator.

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