PyTensor

2.38.2 · active · verified Sat Apr 11

PyTensor (version 2.38.2) is a Python library that functions as an optimizing compiler for evaluating complex mathematical expressions, especially those involving multi-dimensional arrays, on CPUs and GPUs. It is a community-driven fork of Aesara, which itself was a fork of the original Theano project, and serves as the computational backend for the PyMC probabilistic programming library. PyTensor focuses on defining static computational graphs, performing efficient symbolic differentiation, and optimizing execution speed through code generation for C, JAX, or Numba. While it has a somewhat flexible release cadence, it generally aligns with the Scientific Python ecosystem's schedules.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define symbolic variables, build a simple mathematical expression, compile it into a callable PyTensor function, and compute its value and gradient. It showcases PyTensor's core functionality for symbolic computation and automatic differentiation.

import pytensor
import pytensor.tensor as pt
import numpy as np

# Declare two symbolic floating-point scalars
a = pt.dscalar("a")
b = pt.dscalar("b")

# Create a simple expression
c = a + b

# Convert the expression into a callable object
f_c = pytensor.function([a, b], c)

# Evaluate the function
result = f_c(1.5, 2.5)
print(f"a + b = {result}")

# Compute the gradient with respect to 'a'
dc = pytensor.grad(c, a)
f_dc = pytensor.function([a, b], dc)
gradient_result = f_dc(1.5, 2.5)
print(f"Gradient of (a + b) w.r.t. a = {gradient_result}")

view raw JSON →