## scores.utils.TensorPCA


Tensor-based PCA.


Usage

``` python
scores.utils.TensorPCA(
    n_components=0.9, gamma=None, M=None, mode=None, mean_center=True
)
```


Supports standard (linear) PCA and an optional Random Fourier Feature (RFF) mapping prior to PCA.


## Operation Modes

- `linear`: standard linear PCA.
- `rff`: apply a Random Fourier Feature mapping before PCA.

Mode selection follows the constructor arguments: the RFF branch is inferred only when both `gamma` and `M` are provided, unless `mode` is set explicitly. Supplying only one of these values does not enable the RFF mapping by itself.


## Saving / Loading

Persist the module with the standard PyTorch state-dict API. The module registers persistent buffers for PCA and RFF state::

    torch.save(instance.state_dict(), "tpca.pt")

    tpca2 = TensorPCA(n_components=..., gamma=..., M=..., mode=...)
    sd = torch.load("tpca.pt")
    tpca2.load_state_dict(sd)

The custom `_load_from_state_dict` accepts placeholder or differently- shaped tensors and will set or register buffers to avoid size-mismatch errors on fresh instances.


## Notes

PCA internals are stored in `float64` for numerical fidelity. During preprocessing, inputs are cast to `float64` to match the stored mean.

See `https://arxiv.org/pdf/2505.15284` for motivation behind RFF-PCA.


## See Also

[scores.PCAScore](scores.PCAScore.md#seapig.scores.PCAScore)  

[scores.EmbeddingScore](scores.EmbeddingScore.md#seapig.scores.EmbeddingScore)  


## Examples


``` python
import torch
from seapig.scores.utils import TensorPCA
pca = TensorPCA(n_components=0.90)
X = torch.randn(100, 32)
pca.fit(X)
Z = pca.transform(X)        # projected to lower dimension
X_rec, err = pca.reconstruct(X)  # reconstruction and per-sample L2 error
print(err)
```


    tensor([1.4468, 1.3862, 2.0873, 1.5566, 1.1039, 1.5702, 1.2360, 2.2679, 1.7564,
            2.2816, 0.8560, 1.8240, 1.5638, 1.5387, 1.6400, 2.7320, 1.8104, 1.7403,
            1.8922, 1.3271, 1.4992, 2.0017, 0.8434, 2.2082, 1.8579, 1.2735, 1.7480,
            1.3460, 1.9308, 2.2545, 1.7028, 2.8907, 1.2225, 1.5947, 0.9119, 1.6211,
            2.1075, 1.9275, 1.7485, 1.3913, 2.1218, 2.0972, 0.9625, 1.1739, 2.1057,
            1.7747, 1.1935, 1.3640, 2.2466, 1.6397, 2.0592, 1.2691, 1.7305, 1.5413,
            1.8169, 1.4202, 1.7011, 2.1573, 2.5454, 1.7232, 1.4093, 1.2029, 1.6927,
            1.9035, 1.6533, 1.4935, 0.6539, 1.4653, 1.8042, 1.6571, 1.8931, 1.1868,
            1.1219, 1.7392, 1.2887, 1.4660, 1.6753, 1.5730, 2.1402, 1.5524, 1.9517,
            1.7588, 1.9464, 1.9842, 2.1534, 2.3350, 2.1170, 2.3735, 1.8637, 1.5590,
            1.7239, 1.8271, 2.1054, 2.2647, 2.1587, 2.1580, 2.1529, 1.6014, 1.8736,
            1.3300], dtype=torch.float64)


## Methods

| Name | Description |
|----|----|
| [__init__()](#__init__) | Initialise TensorPCA. |
| [finalize()](#finalize) | Finalize partial fit: compute covariance SVD and set PCA params. |
| [fit()](#fit) | Fit PCA on the input data X. |
| [fit_transform()](#fit_transform) | Fit PCA on X and return the projected components. |
| [inverse_transform()](#inverse_transform) | Reconstruct samples from principal component scores. |
| [partial_fit()](#partial_fit) | Process a single batch for incremental PCA. |
| [reconstruct()](#reconstruct) | Reconstruct an input and return the L2 reconstruction error. |
| [reset_partial()](#reset_partial) | Reset internal accumulators used for partial fitting. |
| [transform()](#transform) | Project input samples onto the retained principal components. |

------------------------------------------------------------------------


#### \_\_init\_\_()


Initialise TensorPCA.


Usage

``` python
__init__(n_components=0.9, gamma=None, M=None, mode=None, mean_center=True)
```


##### Parameters


`n_components: int or float = ``0.90`  
If an `int`, the exact number of principal components to retain (must be \> 0). If a `float` in `(0, 1]`, the minimum cumulative explained variance to retain. Defaults to `0.90` (90% variance).

`gamma: float or None = None`  
Bandwidth parameter for the RFF kernel. If provided together with `M`, RFF mode is enabled automatically.

`M: int or None = None`  
Number of RFF random features (must be \> input dimensionality D). If provided together with `gamma`, RFF mode is enabled automatically.

`mode: (linear, rff) = ``"linear"`  
Explicit mode override. When `None`, the mode is inferred from `gamma` and `M`.

`mean_center: bool = ``True`  
Apply mean centering before fitting/transform? Set to False to omit mean centering.


------------------------------------------------------------------------


#### finalize()


Finalize partial fit: compute covariance SVD and set PCA params.


Usage

``` python
finalize()
```


This method computes the overall mean and centred covariance from accumulated sums and performs SVD to extract principal components.


------------------------------------------------------------------------


#### fit()


Fit PCA on the input data X.


Usage

``` python
fit(X, Y=None)
```


Convenience method that runs a single-batch [partial_fit](scores.utils.TensorPCA.md#seapig.scores.utils.TensorPCA.partial_fit) followed by [finalize](scores.utils.TensorPCA.md#seapig.scores.utils.TensorPCA.finalize). For large datasets or streaming data, use the incremental [partial_fit](scores.utils.TensorPCA.md#seapig.scores.utils.TensorPCA.partial_fit) / [finalize](scores.utils.TensorPCA.md#seapig.scores.utils.TensorPCA.finalize) interface instead.


##### Parameters


`X: torch.Tensor`  
Input data of shape `(N, D)`.

`Y: None = None`  
Ignored. Present for API compatibility.


------------------------------------------------------------------------


#### fit_transform()


Fit PCA on X and return the projected components.


Usage

``` python
fit_transform(X, Y=None)
```


##### Parameters


`X: torch.Tensor`  
Input data of shape `(N, D)`.

`Y: None = None`  
Ignored. Present for API compatibility.


##### Returns


`torch.Tensor`  
Projected data of shape `(N, q)` where `q` is the number of retained components.


------------------------------------------------------------------------


#### inverse_transform()


Reconstruct samples from principal component scores.


Usage

``` python
inverse_transform(Z)
```


##### Parameters


`Z: torch.Tensor`  
Component scores of shape `(N, q)`.


##### Returns


`torch.Tensor`  
Reconstructed samples in the preprocessed space, shape `(N, D)` or `(N, M)` if RFF mode is used.


------------------------------------------------------------------------


#### partial_fit()


Process a single batch for incremental PCA.


Usage

``` python
partial_fit(X)
```


This accumulates sufficient statistics (sum of samples and sum of outer products) which are later finalised in [finalize()](scores.utils.TensorPCA.md#seapig.scores.utils.TensorPCA.finalize) to produce the PCA decomposition.


------------------------------------------------------------------------


#### reconstruct()


Reconstruct an input and return the L2 reconstruction error.


Usage

``` python
reconstruct(X)
```


------------------------------------------------------------------------


#### reset_partial()


Reset internal accumulators used for partial fitting.


Usage

``` python
reset_partial()
```


------------------------------------------------------------------------


#### transform()


Project input samples onto the retained principal components.


Usage

``` python
transform(X)
```


##### Parameters


`X: torch.Tensor`  
Input data of shape `(N, D)`.


##### Returns


`torch.Tensor`  
Projected data of shape `(N, q)` where `q` is the number of retained components.
