UNPKG

clustering-tfjs

Version:

High-performance TypeScript clustering algorithms (K-Means, Spectral, Agglomerative) with TensorFlow.js acceleration and scikit-learn compatibility

122 lines 4.61 kB
import type { DataMatrix, LabelVector, SpectralClusteringParams, BaseClustering } from './types'; import * as tf from '../tf-adapter'; export interface LaplacianResult { laplacian: tf.Tensor2D; degrees?: tf.Tensor1D; sqrtDegrees?: tf.Tensor1D; } export interface EmbeddingResult { embedding: tf.Tensor2D; eigenvalues: tf.Tensor1D; rawEigenvectors?: tf.Tensor2D; scalingFactors?: tf.Tensor1D; } export interface IntermediateSteps { affinity: tf.Tensor2D; laplacian: LaplacianResult; embedding: EmbeddingResult; labels: number[]; } export interface DebugInfo { affinityStats?: { shape: number[]; nnz: number; min: number; max: number; mean: number; }; laplacianSpectrum?: number[]; embeddingStats?: { shape: number[]; uniqueValuesPerDim: number[]; scalingFactors?: number[]; }; clusteringMetrics?: { inertia: number; iterations: number; }; } /** * Spectral clustering estimator skeleton. * * This initial implementation only covers: * • Constructor & hyper-parameter validation * • Public instance properties * • Synchronous method stubs for `fit` / `fitPredict` * * The heavy lifting – affinity matrix construction, graph Laplacian * computation, eigen-decomposition and the final k-means step – will be * implemented in subsequent tasks (see backlog). * * Updates introduced in *task-12*: * • Support for `affinity = "precomputed"` and user-supplied callable * affinities with rigorous matrix validation (square, symmetric, * non-negative). * • Public `dispose()` method and automatic clean-up on repeated `fit` * calls to prevent tensor memory leaks. */ export declare class SpectralClustering implements BaseClustering<SpectralClusteringParams> { /** Hyper-parameters (deep-copied from user input). */ readonly params: SpectralClusteringParams; /** Lazy-filled cluster labels after calling `fit`. */ labels_: number[] | null; /** Cached affinity matrix (shape: nSamples × nSamples). */ affinityMatrix_: tf.Tensor2D | null; /** Debug information (populated when using returnIntermediateSteps) */ private debugInfo_; /** Whether to capture debug information (modular compatibility) */ private captureDebugInfo; /** * Disposes any tensors kept as instance state and resets internal caches. * * The estimator instance can still be reused after calling `dispose()` by * invoking `fit` again. */ dispose(): void; private static readonly VALID_AFFINITIES; constructor(params: SpectralClusteringParams & { captureDebugInfo?: boolean; }); /** * Fits the Spectral Clustering model to the input data and stores the * resulting cluster labels in {@link labels_}. * * Pipeline (following scikit-learn implementation): * 1. Build similarity graph – affinity matrix A * 2. Compute normalised Laplacian L = I − D^{-1/2} A D^{-1/2} * 3. Obtain k smallest eigenvectors of L → embedding U (n × k) * 4. Run K-Means directly on the rows of U (no row normalization) * * Note: Row normalization to unit length is only applied when using * assign_labels='discretize', not for the default k-means approach. */ fit(_X: DataMatrix): Promise<void>; fitPredict(X: DataMatrix): Promise<LabelVector>; /** * Get debug information if available. */ getDebugInfo(): DebugInfo | null; /** * Fits the model and returns intermediate steps for debugging and analysis. * This method is useful for comparing with reference implementations. */ fitWithIntermediateSteps(X: DataMatrix): Promise<IntermediateSteps>; private static validateParams; static computeAffinityMatrix(X: tf.Tensor2D, params: SpectralClusteringParams): tf.Tensor2D; /** Returns defaulted k when undefined */ static defaultNeighbors(params: SpectralClusteringParams, nSamples: number): number; /** * Compute spectral embedding from affinity matrix. * Extracted to support parameter sweep. */ private computeEmbeddingFromAffinity; /** * Validates that the provided tensor is a proper affinity / similarity * matrix suitable for spectral clustering. * • Must be 2-D & **square** * • Must be **symmetric** (within tolerance) * • Must be **non-negative** (entries ≥ 0) */ static validateAffinityMatrix(A: tf.Tensor2D): void; } //# sourceMappingURL=spectral.d.ts.map