Skip to Content
OchreML
Decomposition & Manifold

PCA

Principal Component Analysis for linear dimensionality reduction with optional whitening and variance-ratio component selection.

PCA performs linear dimensionality reduction by centering the input feature matrix X and projecting it onto its top principal axes via Singular Value Decomposition (SVD). It supports fixed component counts, automatic variance-threshold selection (0 < n_components < 1), whitening, generative covariance estimation, and probabilistic log-likelihood scoring. (^▽^)

Backend Support

  • Backend primitives: E1–E5 (dense linear algebra / Gram matrices), N1 (column-wise mean & reductions), N5 (eigendecomposition / SVD).
  • Supported devices: "auto", "cpu", "cuda:0", "cuda:all", "wgpu", "tpu:0". Falls back cleanly to multi-threaded Rayon CPU (f64) when an accelerator is unavailable.

Import & Signature

from ochreml.decomposition import PCA
# Or via top-level lazy import:
from ochreml import PCA
PCA(
    n_components: Optional[Union[int, float]] = None,
    whiten: bool = False,
    device: Optional[str] = None,
)

Parameters

ParameterTypeDefaultDescription
n_componentsint, float, or NoneNoneNumber of components to keep. If None, keeps min(n_samples, n_features). If a float in (0.0, 1.0), selects the smallest number of components whose cumulative explained variance ratio exceeds n_components.
whitenboolFalseWhen True, scales projected outputs to have uncorrelated components with unit variance.
devicestr or NoneNoneTarget compute device ("auto", "cpu", "cuda:0", "cuda:all", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device().

Attributes

AttributeType / ShapeDescription
components_ndarray of shape (n_components_, n_features_in_)Principal axes in feature space ordered by decreasing explained variance.
explained_variance_ndarray of shape (n_components_,)Amount of variance explained by each selected component.
explained_variance_ratio_ndarray of shape (n_components_,)Fraction of total variance explained by each selected component.
singular_values_ndarray of shape (n_components_,)Singular values corresponding to each selected component.
mean_ndarray of shape (n_features_in_,)Per-feature empirical mean estimated from the training set.
n_components_intEstimated number of components kept.
n_features_in_intNumber of features seen during fit.
n_samples_intNumber of samples seen during fit.
noise_variance_floatEstimated noise variance under the Probabilistic PCA model.
device_strActive resolved compute device string.

Methods

MethodSignatureDescription
fitfit(X, y=None) -> PCAFit the PCA model on X.
transformtransform(X) -> ndarrayProject X onto the learned principal components.
fit_transformfit_transform(X, y=None) -> ndarrayFit the model on X and return the projected coordinates.
inverse_transforminverse_transform(X) -> ndarrayReconstruct data from reduced component space back to feature space.
get_covarianceget_covariance() -> ndarrayCompute the generative data covariance matrix of shape (n_features_in_, n_features_in_).
score_samplesscore_samples(X) -> ndarrayReturn the Probabilistic PCA log-likelihood of each sample.
scorescore(X, y=None) -> floatReturn the mean log-likelihood across all samples in X.
toto(device) -> PCAMove execution target to a new hardware device.
savesave(path) -> NoneSave the fitted model to a binary .dit file.
loadPCA.load(path, device=None) -> PCALoad a saved PCA model from a .dit file (also supported via ochreml.load).

Example

import numpy as np
import ochreml
from ochreml.decomposition import PCA

rng = np.random.default_rng(42)
X = rng.normal(size=(200, 10))
X[:, 0] *= 5.0
X[:, 1] *= 3.0

pca = PCA(n_components=3, whiten=False, device="auto")
X_reduced = pca.fit_transform(X)
X_reconstructed = pca.inverse_transform(X_reduced)

print("Reduced shape:", X_reduced.shape)
print("Explained variance ratio:", np.round(pca.explained_variance_ratio_, 4))
print("Mean log-likelihood:", round(pca.score(X), 4))

# Persist and reload via native .dit format
pca.save("pca_model.dit")
loaded = ochreml.load("pca_model.dit", device="cpu")
assert np.allclose(X_reduced, loaded.transform(X))

On this page