Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python matrix libraries store matrices and run linear algebra on them, from multiplication and inversion to decompositions and solvers. A sparse format stores only the nonzero entries of a matrix rather than every cell. These libraries let machine learning models, simulations, and data pipelines process large grids of numbers.
Popularity
NumPy has the most monthly downloads in this comparison, at 1.1B.
def row_norms(X, squared=False):
"""Row-wise (squared) Euclidean norm of X.
Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse
matrices and does not create an X.shape-sized temporary.
Performs no input validation.
Parameters
---------- X : array-like
The input array.
squared : bool, default=False
If True, return squared norms.
Returns
------- array-like
The row-wise (squared) Euclidean norm of X.
"""
if sparse.issparse(X):
X = X.tocsr()
norms = csr_row_norms(X)
if not squared:
norms = np.sqrt(norms)
else:
xp, _ = get_namespace(X)
if _is_numpy_namespace(xp):
X = np.asarray(X)
norms = np.einsum("ij,ij->i", X, X)
norms = xp.asarray(norms)
else:
norms = xp.sum(xp.multiply(X, X), axis=1)
if not squared:
norms = xp.sqrt(norms)
return norms
SciPy
Provides sparse matrix storage, numerical solvers, and matrix functions.
Downloads / mo
392.1M
Stars
15.2K
Last release
1.18.1
License
BSD-3-Clause
Strengths
Solves sparse linear systems.Use spsolve with sparse coefficients and vector or matrix right-hand sides.
Computes matrix exponentials.Use expm for the matrix exponential rather than element-wise exponentiation.
Limitations
Sparse arrays need sparse-aware operations.Use sparse operations or convert explicitly before applying NumPy functions.
Incorrect structure hints corrupt solutions.Only set assume_a when the matrix has the stated structure.
import numpy as np
a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
b = np.array([2, 4, -1])
from scipy.linalg import solve
x = solve(a, b)
x
a @ x == b
def scipy_spsolve(A, b):
logger.debug("Scipy Solver - Solving linear system with scipy.sparse.linalg.spsolve")
indptr, indices, data = A.getValuesCSR()
Asp = scipy.sparse.csr_matrix((data, indices, indptr))
# SciPy's spsolve uses UMFPACK only when scikits.umfpack is installed and # applicable; otherwise it falls back to SuperLU. x = scipy.sparse.linalg.spsolve(Asp, onp.array(b))
# TODO: try https://jax.readthedocs.io/en/latest/_autosummary/jax.experimental.sparse.linalg.spsolve.html # x = jax.experimental.sparse.linalg.spsolve(av, aj, ai, b) logger.debug("Scipy Solver - Finished solving, linear solve res = %.3g",
np.linalg.norm(Asp @ x - b))
return x
SymPy
Performs matrix algebra with symbolic entries and exact expressions.
Downloads / mo
169.9M
Stars
15.1K
Last release
1.14.0
License
BSD
Strengths
Works with symbolic matrix entries.Keep symbolic values in matrix calculations.
Returns eigenvalue multiplicities.Use eigenvals for eigenvalues and their algebraic multiplicities.
Limitations
Symbolic zeros can be inconclusive.Pass iszerofunc when simplification cannot identify zero entries.
def focus_of_attention(poses: Float[Tensor, "*num_poses 4 4"], initial_focus: Float[Tensor, "3"]) -> Float[Tensor, "3"]:
"""Compute the focus of attention of a set of cameras. Only cameras
that have the focus of attention in front of them are considered.
Args:
poses: The poses to orient.
initial_focus: The 3D point views to decide which cameras are initially activated.
Returns:
The 3D position of the focus of attention.
"""
# References to the same method in third-party code: # https://github.com/google-research/multinerf/blob/1c8b1c552133cdb2de1c1f3c871b2813f6662265/internal/camera_utils.py#L145 # https://github.com/bmild/nerf/blob/18b8aebda6700ed659cb27a0c348b737a5f6ab60/load_llff.py#L197 active_directions = -poses[:, :3, 2:3]
active_origins = poses[:, :3, 3:4]
# initial value for testing if the focus_pt is in front or behind focus_pt = initial_focus
# Prune cameras which have the current have the focus_pt behind them. active = torch.sum(active_directions.squeeze(-1) * (focus_pt - active_origins.squeeze(-1)), dim=-1) > 0
done = False
# We need at least two active cameras, else fallback on the previous solution. # This may be the "poses" solution if no cameras are active on first iteration, e.g. # they are in an outward-looking configuration. while torch.sum(active.int()) > 1 and not done:
active_directions = active_directions[active]
active_origins = active_origins[active]
# https://en.wikipedia.org/wiki/Line–line_intersection#In_more_than_two_dimensions m = torch.eye(3) - active_directions * torch.transpose(active_directions, -2, -1)
mt_m = torch.transpose(m, -2, -1) @ m
focus_pt = torch.linalg.inv(mt_m.mean(0)) @ (mt_m @ active_origins).mean(0)[:, 0]
active = torch.sum(active_directions.squeeze(-1) * (focus_pt - active_origins.squeeze(-1)), dim=-1) > 0
if active.all():
# the set of active cameras did not change, so we're done. done = True
return focus_pt
Dask Array
Runs PyData workloads in parallel with task scheduling.
def fit_transform(self, X, y=None):
"""Fit model to X and perform dimensionality reduction on X.
Parameters
---------- X : array-like, shape (n_samples, n_features)
Training data.
y : Ignored
Returns
------- X_new : array, shape (n_samples, n_components)
Reduced version of X. This will always be a dense array, of the
same type as the input array. If ``X`` was a ``dask.array``, then
``X_new`` will be a ``dask.array`` with the same chunks along the
first dimension.
"""
X = self._check_array(X)
if self.algorithm not in {"tsqr", "randomized"}:
raise ValueError(
"`algorithm` must be 'tsqr' or 'randomized', not '{}'".format(
self.algorithm
)
)
if self.algorithm == "tsqr":
u, s, v = da.linalg.svd(X)
u = u[:, : self.n_components]
s = s[: self.n_components]
v = v[: self.n_components]
else:
u, s, v = da.linalg.svd_compressed(
X, self.n_components, n_power_iter=self.n_iter, seed=self.random_state
)
if not DASK_2_26_0:
u, v = svd_flip(u, v)
X_transformed = u * s
explained_var = X_transformed.var(axis=0)
full_var = X.var(axis=0).sum()
explained_variance_ratio = explained_var / full_var
if self.compute:
v, explained_var, explained_variance_ratio, s = compute(
v, explained_var, explained_variance_ratio, s
)
self.components_ = v
self.explained_variance_ = explained_var
self.explained_variance_ratio_ = explained_variance_ratio
self.singular_values_ = s
self.n_features_in_ = X.shape[1]
return X_transformed
JAX
Differentiates, compiles, and transforms NumPy code.
def operator_to_matrix(operator_fn, problem):
"""Only used for when debugging.
Can be used to print the matrix, check the conditional number, etc.
"""
J = jax.jacfwd(operator_fn)(np.zeros(problem.num_total_dofs_all_vars))
return J
TensorFlow
Provides an open source machine learning framework.
def sparse_or_dense_matmul(sparse_or_dense_a,
dense_b,
validate_args=False,
name=None,
**kwargs):
"""Returns (batched) matmul of a SparseTensor (or Tensor) with a Tensor.
Args:
sparse_or_dense_a: `SparseTensor` or `Tensor` representing a (batch of)
matrices.
dense_b: `Tensor` representing a (batch of) matrices, with the same batch
shape as `sparse_or_dense_a`. The shape must be compatible with the shape
of `sparse_or_dense_a` and kwargs.
validate_args: When `True`, additional assertions might be embedded in the
graph.
Default value: `False` (i.e., no graph assertions are added).
name: Python `str` prefixed to ops created by this function.
Default value: 'sparse_or_dense_matmul'.
**kwargs: Keyword arguments to `tf.sparse_tensor_dense_matmul` or
`tf.matmul`.
Returns:
product: A dense (batch of) matrix-shaped Tensor of the same batch shape and
dtype as `sparse_or_dense_a` and `dense_b`. If `sparse_or_dense_a` or
`dense_b` is adjointed through `kwargs` then the shape is adjusted
accordingly.
"""
with tf.name_scope(name or 'sparse_or_dense_matmul'):
dense_b = tf.convert_to_tensor(
dense_b, dtype_hint=tf.float32, name='dense_b')
if validate_args:
assert_a_rank_at_least_2 = assert_util.assert_rank_at_least(
sparse_or_dense_a,
rank=2,
message='Input `sparse_or_dense_a` must have at least 2 dimensions.')
assert_b_rank_at_least_2 = assert_util.assert_rank_at_least(
dense_b,
rank=2,
message='Input `dense_b` must have at least 2 dimensions.')
with tf.control_dependencies(
[assert_a_rank_at_least_2, assert_b_rank_at_least_2]):
sparse_or_dense_a = tf.identity(sparse_or_dense_a)
dense_b = tf.identity(dense_b)
if isinstance(sparse_or_dense_a, (tf.SparseTensor, tf1.SparseTensorValue)):
return _sparse_tensor_dense_matmul(sparse_or_dense_a, dense_b, **kwargs)
else:
return tf.matmul(sparse_or_dense_a, dense_b, **kwargs)
PyTensor
Compiles mathematical expressions for evaluation on CPUs and GPUs.
import pytensor
import pytensor.tensor as pt
x = pt.matrix("x")
f = pytensor.function([x], pt.linalg.det(x))
print(f([[1., 2.], [3., 4.]]))
FAQ
NumPy suits dense matrices on the CPU. SciPy suits sparse matrices and adds solvers that work on them. PyTorch and JAX suit matrix work on GPUs and other accelerators.
NumPy multiplies two arrays as matrices with the @ operator or the matmul function.
NumPy represents a matrix as a two-dimensional ndarray, the same array type it uses for every other shape.
SciPy provides sparse arrays and matrices in several storage formats, each with its own operations. The legacy csr_matrix class remains documented alongside the newer sparse arrays.
For coding agents
Found your matrix library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.