Decomposition Pca#
pca
#
| CLASS | DESCRIPTION |
|---|---|
PrincipalComponentAnalysis |
Principal component analysis with optional sample weighting. |
| FUNCTION | DESCRIPTION |
|---|---|
principal_component_analysis |
Perform principal component analysis with optional sample weighting. |
Classes#
PrincipalComponentAnalysis(*, standardize: bool = True, out_features: int = 0)
#
Bases: Decomposition
Principal component analysis with optional sample weighting.
Performs dimensionality reduction by finding the principal components that explain the most variance in the data. Supports weighted samples for cases where observations have different importance.
The algorithm follows these steps:
- Center the data by subtracting the (weighted) mean.
- Optionally standardize features to unit variance.
- Compute the (weighted) covariance matrix.
- Perform eigendecomposition of the covariance matrix.
- Select the top
out_featureseigenvalues and corresponding eigenvectors.
| PARAMETER | DESCRIPTION |
|---|---|
standardize
|
Whether to standardize features before PCA. When True, features are centered and scaled to unit variance.
TYPE:
|
out_features
|
Number of principal components to compute. If 0, computes all components (of shape n_samples). Must be non-negative.
TYPE:
|
Properties
eigenvalues : torch.Tensor Eigenvalues (explained variance) for each component of shape (out_features, ).
eigenvectors : torch.Tensor Eigenvectors (principal component directions) of shape (in_features, out_features).
covariance : torch.Tensor Covariance matrix computed during fitting of shape (in_features, in_features).
mean : torch.Tensor Feature-wise mean computed during fitting of shape (in_features, ).
std : torch.Tensor | None Feature-wise standard deviation if standardize=True, otherwise None. Shape (in_features, ) when available.
explained_variance : torch.Tensor Explained variance for each component.
cumulative_explained_variance : torch.Tensor Cumulative explained variance for components.
Examples:
Basic PCA usage:
>>> import torch
>>> from spectre.decomposition import PCA
>>> X = torch.randn(100, 10) # 100 samples, 10 features
>>> pca = PCA(out_features=3)
>>> pca.fit(X)
>>> X_reduced = pca.predict(X) # Shape: (100, 3)
Weighted PCA:
>>> weights = torch.ones(100) # Equal weights
>>> pca_weighted = PCA(out_features=5, standardize=True)
>>> pca_weighted.fit(X, weights=weights)
>>> explained_var = pca_weighted.explained_variance
References
[1] Stack Exchange: https://stats.stackexchange.com/a/113488
| METHOD | DESCRIPTION |
|---|---|
score |
Compute reconstruction score (negative reconstruction error). |
fit |
Fit PCA to the provided data. |
predict |
Transform data to principal component space. |
inverse_transform |
Transform data back to original space. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
explained_variance |
Proportion of total variance explained by each component.
TYPE:
|
cumulative_explained_variance |
Cumulative proportion of variance explained.
TYPE:
|
eigenvectors |
Eigenvectors of the covariance matrix.
TYPE:
|
eigenvalues |
Eigenvalues of the covariance matrix.
TYPE:
|
covariance |
Covariance matrix of the input data.
TYPE:
|
mean |
Feature-wise mean of the training data.
TYPE:
|
std |
Feature-wise standard deviation (if standardize=True).
TYPE:
|
Source code in spectre/decomposition/pca.py
Attributes#
explained_variance: torch.Tensor
property
#
Proportion of total variance explained by each component.
cumulative_explained_variance: torch.Tensor
property
#
Cumulative proportion of variance explained.
eigenvectors: torch.Tensor
property
#
Eigenvectors of the covariance matrix.
eigenvalues: torch.Tensor
property
#
Eigenvalues of the covariance matrix.
covariance: torch.Tensor
property
#
Covariance matrix of the input data.
mean: torch.Tensor
property
#
Feature-wise mean of the training data.
std: torch.Tensor | None
property
#
Feature-wise standard deviation (if standardize=True).
Functions#
score(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> float
#
Compute reconstruction score (negative reconstruction error).
Returns the negative mean squared reconstruction error, so higher values indicate better reconstruction quality.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data of shape (n_samples, in_features).
TYPE:
|
weights
|
Sample weights of shape (n_samples, ).
TYPE:
|
target
|
Not used in PCA (unsupervised method).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Negative reconstruction error (higher is better). |
Source code in spectre/decomposition/pca.py
fit(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> PrincipalComponentAnalysis
#
Fit PCA to the provided data.
Computes the principal components of the input data, with optional sample weighting. After fitting, the estimator can transform new data.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Training data of shape (n_samples, in_features).
TYPE:
|
weights
|
Sample weights of shape (n_samples, ).
TYPE:
|
target
|
Not used in PCA (unsupervised method).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PrincipalComponentAnalysis
|
Returns self for method chaining. |
Source code in spectre/decomposition/pca.py
predict(X: torch.Tensor) -> torch.Tensor
#
Transform data to principal component space.
Projects the input data onto the fitted principal components, effectively performing dimensionality reduction.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data of shape (n_samples, in_features).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Transformed data of shape (n_samples, out_features). |
Source code in spectre/decomposition/pca.py
inverse_transform(X: torch.Tensor) -> torch.Tensor
#
Transform data back to original space.
Reconstructs the original features from PCA components. Note that this is an approximation if not all components were retained (out_features < in_features).
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Transformed data of shape (n_samples, out_features).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Reconstructed data of shape (n_samples, in_features). |
Source code in spectre/decomposition/pca.py
Functions#
principal_component_analysis(X: torch.Tensor, weights: torch.Tensor | None = None, standardize: bool = True, out_features: int = 0, eps: float = torch.finfo(torch.float32).eps) -> DecompositionResult
#
Perform principal component analysis with optional sample weighting.
Computes the principal components of the input data using eigendecomposition of the covariance matrix. Supports weighted samples and optional standardization.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data of shape (n_samples, in_features). Must be a 2D tensor.
TYPE:
|
weights
|
Sample weights of shape (n_samples, ). If None, all samples have equal weight. When provided, must have same length as X.
TYPE:
|
standardize
|
Whether to standardize features before PCA. When True, features are centered and scaled to unit variance.
TYPE:
|
out_features
|
Number of principal components to compute. If 0, computes all components. Must be non-negative and not exceed min(n_samples, in_features).
TYPE:
|
eps
|
Small value added to std for numerical stability.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DecompositionResult
|
A NamedTuple containing:
|
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If input types are incorrect. |
ValueError
|
If tensor shapes are incompatible or parameters are out of valid ranges. |
Examples:
Basic PCA on random data:
>>> import torch
>>> X = torch.randn(50, 10)
>>> eigenvalues, eigenvectors, cov_matrix = pca(X, out_features=3)
Weighted PCA:
>>> weights = torch.rand(50) # Random weights
>>> result = principal_component_analysis(X, weights=weights, standardize=True)
>>> result.eigenvalues.shape
torch.Size([10])
>>> result.eigenvectors.shape
torch.Size([10, 10])
>>> result.covariance.shape
torch.Size([10, 10])
References
[1] Stack Exchange: https://stats.stackexchange.com/a/113488
Source code in spectre/decomposition/pca.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | |