torch-pca


Nametorch-pca JSON
Version 1.0.0 PyPI version JSON
download
home_pageNone
SummaryPyTorch implementation of PCA (similar to sklearn PCA).
upload_time2024-11-07 10:29:29
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseNone
keywords principal component analysis pca pytorch torch
VCS
bugtrack_url
requirements torch
Travis-CI No Travis.
coveralls test coverage
            # Pytorch Principal Component Analysis (PCA)

Principal Component Anlaysis (PCA) in PyTorch. The intention is to provide a
simple and easy to use implementation of PCA in PyTorch, the most similar to
the `sklearn`'s PCA as possible (in terms of API and, of course, output).
Plus, this implementation is **fully differentiable and faster** (thanks to GPU parallelization)!

[![Release](https://img.shields.io/github/v/tag/valentingol/torch_pca?label=Pypi&logo=pypi&logoColor=yellow)](https://pypi.org/project/torch_pca/)
![PythonVersion](https://img.shields.io/badge/python-3.8%20%7E%203.11-informational)
![PytorchVersion](https://img.shields.io/badge/pytorch-1.8%20%7E%201.13%20%7C%202.0+-informational)

[![GitHub User followers](https://img.shields.io/github/followers/valentingol?label=User%20followers&style=social)](https://github.com/valentingol)
[![GitHub User's User stars](https://img.shields.io/github/stars/valentingol?label=User%20Stars&style=social)](https://github.com/valentingol)

[![Ruff_logo](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v1.json)](https://github.com/charliermarsh/ruff)
[![Black_logo](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

[![Ruff](https://github.com/valentingol/torch_pca/actions/workflows/ruff.yaml/badge.svg)](https://github.com/valentingol/Dinosor/actions/workflows/ruff.yaml)
[![Flake8](https://github.com/valentingol/torch_pca/actions/workflows/flake.yaml/badge.svg)](https://github.com/valentingol/Dinosor/actions/workflows/flake.yaml)
[![MyPy](https://github.com/valentingol/torch_pca/actions/workflows/mypy.yaml/badge.svg)](https://github.com/valentingol/Dinosor/actions/workflows/mypy.yaml)
[![PyLint](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/valentingol/8fb4f3f78584e085dd7b0cca7e046d1f/raw/torch_pca_pylint.json)](https://github.com/valentingol/torch_pca/actions/workflows/pylint.yaml)

[![Tests](https://github.com/valentingol/torch_pca/actions/workflows/tests.yaml/badge.svg)](https://github.com/valentingol/torch_pca/actions/workflows/tests.yaml)
[![Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/valentingol/c5a6b5731db93da673f8e258b2669080/raw/torch_pca_tests.json)](https://github.com/valentingol/torch_pca/actions/workflows/tests.yaml)
[![Documentation Status](https://readthedocs.org/projects/torch-pca/badge/?version=latest)](https://torch-pca.readthedocs.io/en/latest/?badge=latest)

## Links

Github repository: https://github.com/valentingol/torch_pca

Pypi project: https://pypi.org/project/torch_pca/

Documentation: https://torch-pca.readthedocs.io/en/latest/

## Installation

Simply install it with pip:

```bash
pip install torch-pca
```

## How to use

Exactly like `sklearn.decomposition.PCA` but it uses PyTorch tensors as input and output!

```python
from torch_pca import PCA

# Create like sklearn.decomposition.PCA, e.g.:
pca_model = PCA(n_components=None, svd_solver='full')

# Use like sklearn.decomposition.PCA, e.g.:
>>> new_train_data = pca_model.fit_transform(train_data)
>>> new_test_data = pca_model.transform(test_data)
>>> print(pca.explained_variance_ratio_)
[0.756, 0.142, 0.062, ...]
```

More details and features in the [API documentation](https://torch-pca.readthedocs.io/en/latest/api.html#torch_pca.pca_main.PCA).

## Gradient backward pass

Use the pytorch framework allows the automatic differentiation of the PCA!

The PCA transform method is always differentiable so it is always possible to
compute gradient like that:

```python
pca = PCA()
for ep in range(n_epochs):
    optimizer.zero_grad()
    out = neural_net(inputs)
    with torch.no_grad():
        pca.fit(out)
    out = pca.transform(out)
    loss = loss_fn(out, targets)
    loss.backward()
```

If you want to compute the gradient over the full PCA model (including the
fitted `pca.n_components`), you can do it by using the "full" SVD solver
and removing the part of the `fit` method that enforce the deterministic
output by passing `determinist=False` in `fit` or `fit_transform` method.
This part sort the components using the singular values and change their sign
accordingly so it is not differentiable by nature but may be not necessary if
you don't care about the determinism of the output:

```python
pca = PCA(svd_solver="full")
for ep in range(n_epochs):
    optimizer.zero_grad()
    out = neural_net(inputs)
    out = pca.fit_transform(out, determinist=False)
    loss = loss_fn(out, targets)
    loss.backward()
```

## Comparison of execution time with sklearn's PCA

As we can see below the PyTorch PCA is faster than sklearn's PCA, in all the
configs tested with the parameter by default (for each PCA model):

![include](docs/_static/comparison.png)

## Implemented features

- [x] `fit`, `transform`, `fit_transform` methods.
- [x] All attributes from sklean's PCA are available: `explained_variance_(ratio_)`,
      `singular_values_`, `components_`, `mean_`, `noise_variance_`, ...
- [x] Full SVD solver
- [x] SVD by covariance matrix solver
- [x] Randomized SVD solver
- [x] (absent from sklearn) Decide how to center the input data in `transform` method
  (default is like sklearn's PCA)
- [x] Find number of components with explained variance proportion
- [x] Automatically find number of components with MLE
- [x] `inverse_transform` method
- [x] Whitening option
- [x] `get_covariance` method
- [x] `get_precision` method and `score`/`score_samples` methods

## To be implemented

- [ ] Support sparse matrices with ARPACK solver

## Contributing

Feel free to contribute to this project! Just fork it and make an issue or a pull request.

See the [CONTRIBUTING.md](CONTRIBUTING.md) file for more information.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "torch-pca",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "principal component analysis, PCA, pytorch, torch",
    "author": null,
    "author_email": "Valentin Goldite <valentin.goldite@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/17/3b/1d7555229d4ff6aa136fc88f1de55fbcb682cc430f39dee931f34e382020/torch_pca-1.0.0.tar.gz",
    "platform": null,
    "description": "# Pytorch Principal Component Analysis (PCA)\n\nPrincipal Component Anlaysis (PCA) in PyTorch. The intention is to provide a\nsimple and easy to use implementation of PCA in PyTorch, the most similar to\nthe `sklearn`'s PCA as possible (in terms of API and, of course, output).\nPlus, this implementation is **fully differentiable and faster** (thanks to GPU parallelization)!\n\n[![Release](https://img.shields.io/github/v/tag/valentingol/torch_pca?label=Pypi&logo=pypi&logoColor=yellow)](https://pypi.org/project/torch_pca/)\n![PythonVersion](https://img.shields.io/badge/python-3.8%20%7E%203.11-informational)\n![PytorchVersion](https://img.shields.io/badge/pytorch-1.8%20%7E%201.13%20%7C%202.0+-informational)\n\n[![GitHub User followers](https://img.shields.io/github/followers/valentingol?label=User%20followers&style=social)](https://github.com/valentingol)\n[![GitHub User's User stars](https://img.shields.io/github/stars/valentingol?label=User%20Stars&style=social)](https://github.com/valentingol)\n\n[![Ruff_logo](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v1.json)](https://github.com/charliermarsh/ruff)\n[![Black_logo](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n\n[![Ruff](https://github.com/valentingol/torch_pca/actions/workflows/ruff.yaml/badge.svg)](https://github.com/valentingol/Dinosor/actions/workflows/ruff.yaml)\n[![Flake8](https://github.com/valentingol/torch_pca/actions/workflows/flake.yaml/badge.svg)](https://github.com/valentingol/Dinosor/actions/workflows/flake.yaml)\n[![MyPy](https://github.com/valentingol/torch_pca/actions/workflows/mypy.yaml/badge.svg)](https://github.com/valentingol/Dinosor/actions/workflows/mypy.yaml)\n[![PyLint](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/valentingol/8fb4f3f78584e085dd7b0cca7e046d1f/raw/torch_pca_pylint.json)](https://github.com/valentingol/torch_pca/actions/workflows/pylint.yaml)\n\n[![Tests](https://github.com/valentingol/torch_pca/actions/workflows/tests.yaml/badge.svg)](https://github.com/valentingol/torch_pca/actions/workflows/tests.yaml)\n[![Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/valentingol/c5a6b5731db93da673f8e258b2669080/raw/torch_pca_tests.json)](https://github.com/valentingol/torch_pca/actions/workflows/tests.yaml)\n[![Documentation Status](https://readthedocs.org/projects/torch-pca/badge/?version=latest)](https://torch-pca.readthedocs.io/en/latest/?badge=latest)\n\n## Links\n\nGithub repository: https://github.com/valentingol/torch_pca\n\nPypi project: https://pypi.org/project/torch_pca/\n\nDocumentation: https://torch-pca.readthedocs.io/en/latest/\n\n## Installation\n\nSimply install it with pip:\n\n```bash\npip install torch-pca\n```\n\n## How to use\n\nExactly like `sklearn.decomposition.PCA` but it uses PyTorch tensors as input and output!\n\n```python\nfrom torch_pca import PCA\n\n# Create like sklearn.decomposition.PCA, e.g.:\npca_model = PCA(n_components=None, svd_solver='full')\n\n# Use like sklearn.decomposition.PCA, e.g.:\n>>> new_train_data = pca_model.fit_transform(train_data)\n>>> new_test_data = pca_model.transform(test_data)\n>>> print(pca.explained_variance_ratio_)\n[0.756, 0.142, 0.062, ...]\n```\n\nMore details and features in the [API documentation](https://torch-pca.readthedocs.io/en/latest/api.html#torch_pca.pca_main.PCA).\n\n## Gradient backward pass\n\nUse the pytorch framework allows the automatic differentiation of the PCA!\n\nThe PCA transform method is always differentiable so it is always possible to\ncompute gradient like that:\n\n```python\npca = PCA()\nfor ep in range(n_epochs):\n    optimizer.zero_grad()\n    out = neural_net(inputs)\n    with torch.no_grad():\n        pca.fit(out)\n    out = pca.transform(out)\n    loss = loss_fn(out, targets)\n    loss.backward()\n```\n\nIf you want to compute the gradient over the full PCA model (including the\nfitted `pca.n_components`), you can do it by using the \"full\" SVD solver\nand removing the part of the `fit` method that enforce the deterministic\noutput by passing `determinist=False` in `fit` or `fit_transform` method.\nThis part sort the components using the singular values and change their sign\naccordingly so it is not differentiable by nature but may be not necessary if\nyou don't care about the determinism of the output:\n\n```python\npca = PCA(svd_solver=\"full\")\nfor ep in range(n_epochs):\n    optimizer.zero_grad()\n    out = neural_net(inputs)\n    out = pca.fit_transform(out, determinist=False)\n    loss = loss_fn(out, targets)\n    loss.backward()\n```\n\n## Comparison of execution time with sklearn's PCA\n\nAs we can see below the PyTorch PCA is faster than sklearn's PCA, in all the\nconfigs tested with the parameter by default (for each PCA model):\n\n![include](docs/_static/comparison.png)\n\n## Implemented features\n\n- [x] `fit`, `transform`, `fit_transform` methods.\n- [x] All attributes from sklean's PCA are available: `explained_variance_(ratio_)`,\n      `singular_values_`, `components_`, `mean_`, `noise_variance_`, ...\n- [x] Full SVD solver\n- [x] SVD by covariance matrix solver\n- [x] Randomized SVD solver\n- [x] (absent from sklearn) Decide how to center the input data in `transform` method\n  (default is like sklearn's PCA)\n- [x] Find number of components with explained variance proportion\n- [x] Automatically find number of components with MLE\n- [x] `inverse_transform` method\n- [x] Whitening option\n- [x] `get_covariance` method\n- [x] `get_precision` method and `score`/`score_samples` methods\n\n## To be implemented\n\n- [ ] Support sparse matrices with ARPACK solver\n\n## Contributing\n\nFeel free to contribute to this project! Just fork it and make an issue or a pull request.\n\nSee the [CONTRIBUTING.md](CONTRIBUTING.md) file for more information.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "PyTorch implementation of PCA (similar to sklearn PCA).",
    "version": "1.0.0",
    "project_urls": {
        "Source": "https://github.com/valentingol/torch_pca"
    },
    "split_keywords": [
        "principal component analysis",
        " pca",
        " pytorch",
        " torch"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "272bf55212458f8b0349683beb0c6c6284ef4548771148a3fd03f520817a3888",
                "md5": "b4c8d67c7a45b7d00ebb67d928475c21",
                "sha256": "e49f7dc031528749c4564682c38e919ec8286565073059699aeda420838c0186"
            },
            "downloads": -1,
            "filename": "torch_pca-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b4c8d67c7a45b7d00ebb67d928475c21",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 12939,
            "upload_time": "2024-11-07T10:29:28",
            "upload_time_iso_8601": "2024-11-07T10:29:28.265986Z",
            "url": "https://files.pythonhosted.org/packages/27/2b/f55212458f8b0349683beb0c6c6284ef4548771148a3fd03f520817a3888/torch_pca-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "173b1d7555229d4ff6aa136fc88f1de55fbcb682cc430f39dee931f34e382020",
                "md5": "c0114c9a9df5abec6df89337938d3b5f",
                "sha256": "138fe51bed8935cbb9a9042915558f1e98779b78c38dddfe8f9d95a8cd9cf464"
            },
            "downloads": -1,
            "filename": "torch_pca-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "c0114c9a9df5abec6df89337938d3b5f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 91643,
            "upload_time": "2024-11-07T10:29:29",
            "upload_time_iso_8601": "2024-11-07T10:29:29.637722Z",
            "url": "https://files.pythonhosted.org/packages/17/3b/1d7555229d4ff6aa136fc88f1de55fbcb682cc430f39dee931f34e382020/torch_pca-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-07 10:29:29",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "valentingol",
    "github_project": "torch_pca",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [
        {
            "name": "torch",
            "specs": []
        }
    ],
    "lcname": "torch-pca"
}
        
Elapsed time: 0.48946s