TensorLy

0.9.0 · active · verified Tue Apr 14

TensorLy is a Python library designed to simplify and make tensor learning accessible, offering tools for tensor decomposition, tensor learning, and tensor algebra. It features a flexible backend system that allows computations to be seamlessly performed using NumPy (default), PyTorch, JAX, TensorFlow, CuPy, or Paddle, enabling scalable operations on both CPU and GPU. The library is actively maintained, with its latest version 0.9.0 released in November 2024, and regular updates bringing new features and improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize TensorLy, create a tensor, optionally set a backend, perform a CANDECOMP/PARAFAC (CP) decomposition, and reconstruct the tensor from the learned factors.

import tensorly as tl
import numpy as np
from tensorly.decomposition import parafac

# Set the backend (optional, defaults to numpy)
tl.set_backend('numpy') # Or 'pytorch', 'jax', 'tensorflow', 'cupy', 'paddle'

# Create a random tensor
# tensor = tl.random.random_tensor((3, 4, 2))
# Create a tensor from a NumPy array
tensor = tl.tensor(np.arange(24).reshape((3, 4, 2)), dtype=tl.float64)

print(f"Original tensor shape: {tensor.shape}")

# Perform CP decomposition
rank = 2
factors = parafac(tensor, rank=rank)

# Reconstruct the tensor from factors
reconstructed_tensor = tl.cp_to_tensor(factors)

print(f"Reconstructed tensor shape: {reconstructed_tensor.shape}")
print(f"Reconstruction error: {tl.norm(tensor - reconstructed_tensor) / tl.norm(tensor):.4f}")

view raw JSON →