Skip to main content

A fast Python library for Randomized Singular Value Decomposition (rSVD).

Project description

randomized-svd: Fast Randomized SVD implemented in Python

Python Version License Build Status Code Style

randomized-svd is a lightweight, high-performance Python library for computing the Randomized Singular Value Decomposition (rSVD).

It is designed to handle massive matrices efficiently by decomposing them into a smaller, random subspace before computing the SVD. This approach is significantly faster than deterministic methods (like LAPACK's dgesdd) while maintaining high numerical accuracy for low-rank approximations.

Original Research: This library is the engineering implementation of the thesis "A Randomized Algorithm for SVD Calculation" (M. Fedrigo). You can read the full theoretical background in the docs/thesis.pdf.


๐Ÿš€ Key Features

  • Smart Dispatching: Automatically selects the optimal algorithm strategy for "Tall-and-Skinny" ($m \ge n$) vs "Short-and-Fat" ($m < n$) matrices to minimize memory footprint.
  • Randomized PCA (New): Performs Principal Component Analysis with Virtual Centering. It computes PCA on sparse matrices without ever materializing the dense centered matrix ($X - \mu$), saving gigabytes of RAM.
  • Scikit-Learn Compatible: Features a RandomizedSVD class wrapper that acts as a drop-in replacement for TruncatedSVD. Works natively with Pipelines and GridSearchCV.
  • Sparse Matrix Support: Natively supports scipy.sparse matrices (CSR/CSC). It performs matrix multiplications without ever densifying the data.
  • Automatic Denoising: Includes an implementation of the Gavish-Donoho method for optimal hard thresholding.
  • Robustness: Uses internal Oversampling to ensure the target singular vectors are captured correctly, minimizing the probability of approximation errors.
  • Production Ready: Fully type-hinted, unit-tested, and packaged with modern standards (pyproject.toml).

๐Ÿ›  Installation

Choose the installation method based on your needs.

๐Ÿ“ฆ For Users (Standard Usage)

If you just want to use the library in your own project:

  1. Activate your project's virtual environment (recommended).
  2. Install from PyPI:
pip install randomized-svd

๐Ÿ’ป For Developers (Contributing)

If you want to run tests, modify the code, or contribute:

  1. Clone the repository:
git clone https://github.com/massimofedrigo/randomized-svd.git
cd randomized-svd
  1. Create and Activate a Virtual Environment: Linux / macOS:
python3 -m venv venv
source venv/bin/activate

Windows (PowerShell):

python -m venv venv
.\venv\Scripts\activate
  1. Install in Editable Mode: This installs the package along with testing dependencies (pytest, etc.) and reflects code changes immediately.
pip install -e ".[dev]"

โšก Quick Start

1. Basic Decomposition

Compute the approximated SVD of a generic matrix.

import numpy as np
from randomized_svd import rsvd

# Generate a large random matrix (1000 x 500)
X = np.random.randn(1000, 500)

# Compute rSVD with target rank k=10
U, S, Vt = rsvd(X, t=10)

print(f"U shape: {U.shape}")    # (1000, 10)
print(f"S shape: {S.shape}")    # (10, 10)
print(f"Vt shape: {Vt.shape}")  # (10, 500)

2. Automatic Noise Reduction (Denoising)

Use the Gavish-Donoho optimal threshold to remove white noise from a signal.

import numpy as np
from randomized_svd import rsvd, optimal_threshold

# Create a synthetic noisy signal
X_true = np.random.randn(1000, 10) @ np.random.randn(10, 500)
X_noisy = X_true + 0.5 * np.random.randn(1000, 500)

# Calculate optimal rank based on noise level (gamma)
target_rank = optimal_threshold(m=1000, n=500, gamma=0.5)

# Clean the matrix using the optimal rank
U, S, Vt = rsvd(X_noisy, t=target_rank)
X_clean = U @ S @ Vt

3. Sparse Matrices (Memory Efficient)

For Recommender Systems or NLP, matrices are often huge but sparse. rsvd handles scipy.sparse objects directly, saving RAM.

import scipy.sparse as sp
from randomized_svd import rsvd

# Create a massive 10k x 10k matrix with 1% density
X_sparse = sp.rand(10000, 10000, density=0.01, format='csr')

# Compute SVD directly (fast & memory efficient)
U, S, Vt = rsvd(X_sparse, t=50)

print(f"Computed {len(S)} singular values without OOM errors.")

4. High Accuracy Mode

For matrices with slowly decaying singular values (flat spectrum), standard randomized projections might miss some information. You can improve accuracy using Power Iterations (p) and Oversampling.

  • p (Power Iterations): Exponentiates the singular values to make them "pop out" more clearly.
  • oversampling: Projects onto a slightly larger subspace () to create a safety buffer, which is truncated at the end.
import numpy as np
from randomized_svd import rsvd

X = np.random.randn(1000, 500)

# Compute rSVD with:
# - Target rank t=10
# - Power iterations p=2 (Recommended for slowly decaying spectra)
# - Oversampling=20 (Compute 30 components internally, return best 10)
U, S, Vt = rsvd(X, t=10, p=2, oversampling=20)

5. Scikit-Learn API (Pipelines & GridSearch)

Use the RandomizedSVD class to integrate seamlessly with Scikit-Learn pipelines.

from randomized_svd import RandomizedSVD
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

# Create a pipeline: Scale data -> Reduce Dimensions
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('rsvd', RandomizedSVD(n_components=10, random_state=42))
])

# Fit and Transform in one go
X_reduced = pipeline.fit_transform(X)

6. Randomized PCA (Virtual Centering)

Perform PCA on sparse data without centering explicitly (which would destroy sparsity). rpca handles this automatically.

import scipy.sparse as sp
from randomized_svd import rpca

# Sparse matrix with non-zero mean
X_sparse = sp.rand(1000, 1000, density=0.01, format='csr')

# Compute PCA directly
# This avoids creating the dense (X - mean) matrix in memory
U, S, Vt = rpca(X_sparse, t=10)

๐Ÿ— Project Structure

The project follows a modern src-layout to prevent import errors and ensure clean packaging.

randomized-svd/
โ”œโ”€โ”€ .github/workflows/    # CI/CD pipelines
โ”œโ”€โ”€ docs/                 # Thesis PDF and extra documentation
โ”œโ”€โ”€ examples/             # Jupyter Notebooks (Demos & Benchmarks)
โ”œโ”€โ”€ src/                  # Source code
โ”‚   โ””โ”€โ”€ randomized_svd/   # Package source
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ”œโ”€โ”€ core.py       # Main rSVD logic (Facade & Implementations)
โ”‚       โ”œโ”€โ”€ pca.py        # Randomized PCA & Virtual Centering
โ”‚       โ”œโ”€โ”€ sklearn.py    # Scikit-Learn Wrapper
โ”‚       โ””โ”€โ”€ utils.py      # Math helpers (Gavish-Donoho threshold)
โ”œโ”€โ”€ tests/                # Pytest suite
โ”œโ”€โ”€ Dockerfile            # Reproducible testing environment
โ”œโ”€โ”€ pyproject.toml        # Dependencies and metadata (replaces setup.py)
โ””โ”€โ”€ README.md

๐Ÿณ Docker Support

To ensure reproducibility across different machines and operating systems, we provide a Dockerfile.

Note: Docker is primarily used here for running the test suite in an isolated, clean environment. For using the library in your own projects, the standard pip install (above) is recommended.

Build the image:

docker build -t randomized-svd-test .

Run the test suite:

docker run randomized-svd-test

๐Ÿ“ˆ Performance

Benchmarks run on an Intel i7, 16GB RAM.

Matrix Size Method Time (s) Speedup
5000 x 5000 rSVD (k=50) 0.82s ~12x
5000 x 5000 NumPy SVD 9.94s -

See examples/2_benchmark_performance.ipynb for the full reproduction script.


๐Ÿงช Testing

We use pytest for unit testing, covering:

  1. Invariance: Output dimensions match mathematical expectations.
  2. Accuracy: Reconstruction error on low-rank matrices is negligible.
  3. Orthogonality: and matrices are verified to be orthogonal.

Run tests locally (requires dev installation):

pytest -v

๐Ÿ“š References

  1. Fedrigo, M. (2024). A Randomized Algorithm for SVD Calculation. PDF Available.
  2. Halko, N., Martinsson, P. G., & Tropp, J. A. (2011). Finding structure with randomness: Probabilistic algorithms for constructing approximate matrix decompositions. SIAM review.
  3. Gavish, M., & Donoho, D. L. (2014). The optimal hard threshold for singular values is $4/\sqrt{3}$.
  4. Brunton, S. L., & Kutz, N. J. (2019). Data-Driven Science and Engineering: Machine Learning, Dynamical Systems, and Control.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Author: Massimo Fedrigo

Portfolio & Research: massimofedrigo.com

Contact: contact@massimofedrigo.com

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

randomized_svd-0.4.0.tar.gz (19.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

randomized_svd-0.4.0-py3-none-any.whl (13.7 kB view details)

Uploaded Python 3

File details

Details for the file randomized_svd-0.4.0.tar.gz.

File metadata

  • Download URL: randomized_svd-0.4.0.tar.gz
  • Upload date:
  • Size: 19.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for randomized_svd-0.4.0.tar.gz
Algorithm Hash digest
SHA256 f428f72f481fe9c56599bb570b74023397121a103d614f3ef4c50d82b6e6a75c
MD5 c85c782b9c081a2dd8f148852fe8fabd
BLAKE2b-256 41475624304ecaae00026b04ffe456c43de5c036ad1f04bc486f7d367739dbdf

See more details on using hashes here.

File details

Details for the file randomized_svd-0.4.0-py3-none-any.whl.

File metadata

  • Download URL: randomized_svd-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 13.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for randomized_svd-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 85e4b470af2ff14cc6bf3232774cd9b57a783418a12d4437424ac30116f35d1c
MD5 e66e0a4ee38a313b4ad2184c71089ccb
BLAKE2b-256 c2f075e0f0c64e3c3fbf30d513835ccc5926281c4cf9668d154c583e914badc6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page