Dimensionality Reduction
Overview
The dimensionality reduction module provides algorithms that project high-dimensional TensorData into a lower-dimensional space while preserving structure. These algorithms extend the MLModelOperation hierarchy via the MLDimReductionOperation abstract base class.
Architecture
models/
├── MLDimReductionOperation.hpp # Abstract base with fitTransform/transform
└── unsupervised/
├── PCAOperation.hpp/.cpp # Principal Component Analysis (manual eigendecomp)
├── RobustPCAOperation.hpp/.cpp # Robust PCA via ROSL (Armadillo)
├── rosl.hpp # Third-party ROSL algorithm (GPL3)
├── TSNEOperation.hpp/.cpp # t-SNE (tapkee)
└── ICAOperation.hpp/.cpp # ICA via RADICAL (mlpack)
MLDimReductionOperation
MLDimReductionOperation extends MLModelOperation with dimensionality-reduction-specific pure virtual methods:
| Method | Purpose |
|---|---|
fitTransform(features, params, result) |
Fit model and project data in one call |
transform(features, result) |
Re-project new data using fitted model |
outputDimensions() |
Number of output dimensions after reduction |
explainedVarianceRatio() |
Per-component variance explained (PCA-specific) |
The base class overrides getTaskType() → MLTaskType::DimensionalityReduction and routes the standard fit() method to fitTransform().
Data Convention
MLCore uses the mlpack convention: matrices are (features × observations) — each column is one observation. TensorData uses the opposite: (observations × features). The TransformsV2 wrapper handles the transpose.
PCAOperation
Implements PCA via manual eigendecomposition on the covariance matrix:
- Center data by subtracting column means
- Compute covariance matrix
- Eigendecomposition via
arma::eig_sym - Sort eigenvectors in descending eigenvalue order
- Truncate to
n_components - Project:
eigenvectors.t() * centered_data
Feature scaling (z-score normalization) is the caller’s responsibility and should be applied before calling fitTransform(). PCA only centers internally — it no longer scales internally. See the Feature Scaling Roadmap for rationale.
Parameters
| Field | Type | Default | Description |
|---|---|---|---|
n_components |
size_t |
2 | Number of principal components to retain |
Save/Load
Uses cereal binary serialization, matching the pattern established by KMeansOperation. Stores eigenvectors, eigenvalues, mean, and total variance.
Edge Cases
- Empty data → returns
false - Fewer than 2 observations → returns
false n_components > features→ returnsfalsen_components = 0→ returnsfalse
TransformsV2 Integration
The TensorPCA container transform (src/TransformsV2/algorithms/TensorPCA/) provides a thin wrapper registered in RegisteredTransforms.cpp:
- Input:
TensorData(2D, ≥2 rows) - Output:
TensorDatawithn_componentscolumns named “PC1”, “PC2”, … - RowDescriptor preservation: Output inherits the input’s
RowType(TimeFrameIndex, Interval, or Ordinal)
TensorPCAParams (reflect-cpp)
| Field | Type | Default | Description |
|---|---|---|---|
n_components |
optional<size_t> |
2 | Number of PCs |
TSNEOperation
Implements t-distributed Stochastic Neighbor Embedding via the tapkee library. t-SNE is a non-linear, stochastic method well suited for 2D/3D visualization of high-dimensional data.
Backend
Tapkee is a header-only C++ dimensionality reduction library. It is fetched via FetchContent in external/CMakeLists.txt but its own CMakeLists.txt is not processed — instead, a lightweight tapkee_headers INTERFACE target is created manually, linking Eigen3::Eigen and fmt::fmt-header-only.
Implementation
- Convert Armadillo matrix (features × observations) → Eigen matrix (same layout, both column-major)
- Call
tapkee::with(...).embedUsing(eigen_data)withtDistributedStochasticNeighborEmbeddingmethod - Convert Eigen output → Armadillo result (n_components × observations)
The sne_theta parameter controls Barnes-Hut approximation: theta > 0 enables the O(N log N) approximation, theta == 0 uses exact O(N²) computation.
Parameters
| Field | Type | Default | Description |
|---|---|---|---|
n_components |
size_t |
2 | Output dimensions (usually 2 or 3) |
perplexity |
double |
30.0 | Effective neighborhood size (5–50 typical) |
theta |
double |
0.5 | Barnes-Hut angle (0 = exact, >0 = faster) |
Limitations
- No out-of-sample projection:
transform()always returnsfalse. t-SNE is transductive — it embeds only the data it was fit on. - No explained variance:
explainedVarianceRatio()returns empty (not meaningful for t-SNE). - Stochastic: Results vary between runs (no seed parameter exposed yet).
- Perplexity auto-clamping: If
perplexity ≥ n_observations / 3, it is clamped internally.
Edge Cases
- Empty data → returns
false - Fewer than 4 observations → returns
false n_components = 0→ returnsfalse- Excessive perplexity → automatically clamped
TransformsV2 Integration: TensorTSNE
The TensorTSNE container transform (src/TransformsV2/algorithms/TensorTSNE/) provides a thin wrapper registered in RegisteredTransforms.cpp:
- Input:
TensorData(2D, ≥4 rows) - Output:
TensorDatawithn_componentscolumns named “tSNE1”, “tSNE2”, … - RowDescriptor preservation: Output inherits the input’s
RowType(TimeFrameIndex, Interval, or Ordinal) - Non-deterministic:
is_deterministic = falsein the registration metadata
TensorTSNEParams (reflect-cpp)
| Field | Type | Default | Description |
|---|---|---|---|
n_components |
optional<size_t> |
2 | Output dimensions |
perplexity |
optional<double> |
30.0 | SNE perplexity |
theta |
optional<double> |
0.5 | Barnes-Hut angle |
RobustPCAOperation
Implements Robust PCA via the ROSL (Robust Online Subspace Learning) algorithm. Unlike standard PCA, Robust PCA decomposes the data matrix into a low-rank component and a sparse error component: X = A + E. This makes it resilient to sparse outliers and gross corruptions that would distort standard PCA.
Backend
Uses the header-only rosl.hpp by Tom Furnival (GPL3 license), which depends only on Armadillo. No additional external dependencies are needed.
Implementation
- Center data by subtracting feature means
- Run ROSL to decompose:
centered = A + E(low-rank + sparse error) - SVD on the low-rank component
Ato get orthogonal principal directions - Take the top
n_componentsleft-singular vectors as eigenvectors - Project:
eigenvectors.t() * centered_data
The lambda parameter controls the sparsity penalty on the error matrix. When set to 0 (default), it is auto-computed as 1 / sqrt(max(m, n)), which is the theoretically optimal value for Robust PCA.
Parameters
| Field | Type | Default | Description |
|---|---|---|---|
n_components |
size_t |
2 | Number of components to retain |
lambda |
double |
0.0 | Sparsity regularization (0 = auto: 1/sqrt(max(m,n))) |
tol |
double |
1e-5 | Convergence tolerance for ALM iterations |
max_iter |
size_t |
100 | Maximum ALM iterations |
Capabilities
- Out-of-sample projection:
transform()is supported — new data is centered and projected via the learned eigenvectors. - Explained variance:
explainedVarianceRatio()returns per-component variance from the SVD singular values of the low-rank component. - Deterministic: Fixed seed (42) for reproducibility.
Edge Cases
- Empty data → returns
false - Fewer than 2 observations → returns
false n_components > features→ returnsfalsen_components = 0→ returnsfalse
Save/Load
Uses cereal binary serialization storing eigenvectors, eigenvalues, mean, total variance, and component count.
TransformsV2 Integration: TensorRobustPCA
The TensorRobustPCA container transform (src/TransformsV2/algorithms/TensorRobustPCA/) provides a thin wrapper registered in RegisteredTransforms.cpp:
- Input:
TensorData(2D, ≥2 rows) - Output:
TensorDatawithn_componentscolumns named “RPCA1”, “RPCA2”, … - RowDescriptor preservation: Output inherits the input’s
RowType(TimeFrameIndex, Interval, or Ordinal) - Deterministic:
is_deterministic = truein the registration metadata
TensorRobustPCAParams (reflect-cpp)
| Field | Type | Default | Description |
|---|---|---|---|
n_components |
optional<size_t> |
2 | Number of output components |
lambda |
optional<double> |
0.0 | Sparsity regularization (0 = auto) |
tol |
optional<double> |
1e-5 | Convergence tolerance |
max_iter |
optional<size_t> |
100 | Maximum iterations |
TransformsV2 Integration: TensorPCA
The TensorPCA container transform (src/TransformsV2/algorithms/TensorPCA/) provides a thin wrapper registered in RegisteredTransforms.cpp:
- Input:
TensorData(2D, ≥2 rows) - Output:
TensorDatawithn_componentscolumns named “PC1”, “PC2”, … - RowDescriptor preservation: Output inherits the input’s
RowType(TimeFrameIndex, Interval, or Ordinal)
TensorPCAParams (reflect-cpp)
| Field | Type | Default | Description |
|---|---|---|---|
n_components |
optional<size_t> |
2 | Number of PCs |
ICAOperation
Implements Independent Component Analysis (ICA) via mlpack’s RADICAL (Robust, Accurate, Direct ICA aLgorithm). Unlike PCA, which finds uncorrelated components ordered by variance, ICA finds components that are statistically independent.
Backend
Uses mlpack::Radical, which is included in the mlpack headers already used by the project.
Implementation
- Call
mlpack::Radical::Apply(features, independent, unmixing)to decompose the input - Store the learned unmixing matrix
Wfor projecting new data:Y = W * X
Parameters
| Field | Type | Default | Description |
|---|---|---|---|
noise_std_dev |
double |
0.175 | Standard deviation of Gaussian noise added to data |
replicates |
size_t |
30 | Number of Gaussian-perturbed replicates per point |
angles |
size_t |
150 | Number of angles in brute-force search during 2D RADICAL |
sweeps |
size_t |
0 | Number of sweeps (0 = dimensions - 1) |
m |
size_t |
0 | Vasicek’s m-spacing estimator parameter (0 = sqrt(dimensions)) |
Capabilities
- Out-of-sample projection:
transform()is supported — new data is projected via the learned unmixing matrix. - Explained variance:
explainedVarianceRatio()returns empty (not meaningful for ICA). - No dimensionality reduction: Output has the same number of dimensions as the input. Each output dimension is an independent component.
Edge Cases
- Empty data → returns
false - Fewer than 2 observations → returns
false
Save/Load
Uses cereal binary serialization storing the unmixing matrix and feature count.
Performance Notes
RADICAL scales quadratically in the number of input dimensions. For high-dimensional data, consider reducing dimensionality with PCA first.
TransformsV2 Integration: TensorICA
The TensorICA container transform (src/TransformsV2/algorithms/TensorICA/) provides a thin wrapper registered in RegisteredTransforms.cpp:
- Input:
TensorData(2D, ≥2 rows, ≥2 cols) - Output:
TensorDatawith same number of columns as input, named “IC1”, “IC2”, … - RowDescriptor preservation: Output inherits the input’s
RowType(TimeFrameIndex, Interval, or Ordinal) - Non-deterministic:
is_deterministic = falsein the registration metadata (RADICAL adds random noise)
TensorICAParams (reflect-cpp)
| Field | Type | Default | Description |
|---|---|---|---|
noise_std_dev |
double |
0.175 | Gaussian noise std dev |
replicates |
size_t |
30 | Number of replicates per point |
angles |
size_t |
150 | Number of angles for 2D search |
sweeps |
size_t |
0 | Number of sweeps (0 = auto) |
nan_policy |
NaNPolicy |
Propagate | How to handle NaN/Inf rows |
Tests
tests/MLCore/PCAOperation.test.cpp— Metadata, fitTransform correctness, explained variance, transform re-projection, edge cases, save/load round-trip, registry integrationtests/MLCore/TSNEOperation.test.cpp— Metadata, fitTransform shape, transform unsupported, edge cases (empty, too few, zero n_components, excessive perplexity), default parameterstests/MLCore/RobustPCAOperation.test.cpp— Metadata, fitTransform shape (clean and outlier data), explained variance ordering, transform re-projection, dimension mismatch rejection, edge cases (empty, too few, zero/excessive n_components), default parameters, save/load round-tripsrc/TransformsV2/algorithms/TensorPCA/TensorPCA.test.cpp— Container registration, ordinal/TimeFrameIndex/Interval row preservation, default params, validation, progress, cancellationsrc/TransformsV2/algorithms/TensorTSNE/TensorTSNE.test.cpp— Container registration, ordinal/TimeFrameIndex row preservation, validation, progress, cancellationsrc/TransformsV2/algorithms/TensorRobustPCA/TensorRobustPCA.test.cpp— Container registration, ordinal/TimeFrameIndex row preservation, validation (too few rows, excessive components), progress, cancellationsrc/TransformsV2/algorithms/TensorICA/TensorICA.test.cpp— Container registration, ordinal/TimeFrameIndex/Interval row preservation, validation (too few rows, too few cols), progress, cancellation