jax.numpy.vectorize#

jax.numpy.vectorize(pyfunc, *, excluded=frozenset({}), signature=None)[源代码]#

定义一个支持广播的向量化函数。

vectorize() 是一个方便的包装器,用于定义具有广播功能的矢量化函数,风格类似于 NumPy 的 通用函数。它允许定义自动跨任何前导维度重复的函数,而无需函数实现者关心如何处理高维输入。

jax.numpy.vectorize() 的接口与 numpy.vectorize 相同,但它是一个自动批处理转换(vmap())的语法糖,而不是 Python 循环。这应该更有效率,但实现必须使用作用于 JAX 数组的函数来编写。

参数:
  • pyfunc – 要矢量化的函数。

  • excluded – 可选的整数集,表示函数不会对其进行矢量化的位置参数。这些参数将原样直接传递给 pyfunc

  • signature – 可选的通用函数签名,例如,用于矢量化矩阵向量乘法的 (m,n),(n)->(m)。如果提供,pyfunc 将以由相应核心维度的大小给出的数组进行调用(并期望返回)。默认情况下,假设 pyfunc 接受标量数组作为输入,并且如果 signatureNone,则 pyfunc 可以产生任何形状的输出。

返回:

给定函数的矢量化版本。

示例

以下是一些使用 vectorize() 编写矢量化线性代数例程的示例

>>> from functools import partial
>>> @partial(jnp.vectorize, signature='(k),(k)->(k)')
... def cross_product(a, b):
...   assert a.shape == b.shape and a.ndim == b.ndim == 1
...   return jnp.array([a[1] * b[2] - a[2] * b[1],
...                     a[2] * b[0] - a[0] * b[2],
...                     a[0] * b[1] - a[1] * b[0]])
>>> @partial(jnp.vectorize, signature='(n,m),(m)->(n)')
... def matrix_vector_product(matrix, vector):
...   assert matrix.ndim == 2 and matrix.shape[1:] == vector.shape
...   return matrix @ vector

这些函数仅为处理一维或二维数组而编写(assert 语句永远不会被违反),但使用 vectorize,它们支持具有 NumPy 风格广播功能的任意维度输入,例如:

>>> cross_product(jnp.ones(3), jnp.ones(3)).shape
(3,)
>>> cross_product(jnp.ones((2, 3)), jnp.ones(3)).shape
(2, 3)
>>> cross_product(jnp.ones((1, 2, 3)), jnp.ones((2, 1, 3))).shape
(2, 2, 3)
>>> matrix_vector_product(jnp.ones(3), jnp.ones(3))  
Traceback (most recent call last):
ValueError: input with shape (3,) does not have enough dimensions for all
core dimensions ('n', 'k') on vectorized function with excluded=frozenset()
and signature='(n,k),(k)->(k)'
>>> matrix_vector_product(jnp.ones((2, 3)), jnp.ones(3)).shape
(2,)
>>> matrix_vector_product(jnp.ones((2, 3)), jnp.ones((4, 3))).shape
(4, 2)

请注意,这与 jnp.matmul 的语义不同。

>>> jnp.matmul(jnp.ones((2, 3)), jnp.ones((4, 3)))  
Traceback (most recent call last):
TypeError: dot_general requires contracting dimensions to have the same shape, got [3] and [4].