tensor.extra_ops
– Tensor Extra Ops#
- pytensor.tensor.extra_ops.bartlett(M)[source]#
An instance of this class returns the Bartlett spectral window in the time-domain. The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain.
New in version 0.6.
- Parameters:
M (integer scalar) – Number of points in the output window. If zero or less, an empty vector is returned.
- Returns:
The triangular window, with the maximum value normalized to one (the value one appears only if the number of samples is odd), with the first and last samples equal to zero.
- Return type:
vector of doubles
- pytensor.tensor.extra_ops.bincount(x, weights=None, minlength=None, assert_nonneg=False)[source]#
Count number of occurrences of each value in an array of integers.
The number of bins (of size 1) is one larger than the largest value in
x
. If minlength is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents ofx
). Each bin gives the number of occurrences of its index value inx
. Ifweights
is specified the input array is weighted by it, i.e. if a valuen
is found at positioni
,out[n] += weight[i]
instead ofout[n] += 1
.- Parameters:
x – A one dimensional array of non-negative integers
weights – An array of the same shape as
x
with corresponding weights. Optional.minlength – A minimum number of bins for the output array. Optional.
assert_nonneg – A flag that inserts an
assert_op
to check if every inputx
is non-negative. Optional.versionadded: (..) – 0.6:
- pytensor.tensor.extra_ops.broadcast_arrays(*args: TensorVariable) tuple[pytensor.tensor.variable.TensorVariable, ...] [source]#
Broadcast any number of arrays against each other.
- Parameters:
*args – The arrays to broadcast.
- pytensor.tensor.extra_ops.broadcast_shape(*arrays, **kwargs) tuple[pytensor.scalar.basic.ScalarVariable, ...] [source]#
Compute the shape resulting from broadcasting arrays.
- Parameters:
*arrays (TensorVariable) – The tensor variables, or their shapes (as tuples), for which the broadcast shape is computed.
arrays_are_shapes (bool (Optional)) – Indicates whether or not the
arrays
contains shape tuples. If you use this approach, make sure that the broadcastable dimensions are (scalar) constants with the value1
–or simply the integer1
.
- pytensor.tensor.extra_ops.broadcast_to(x: TensorVariable, shape: pytensor.tensor.variable.TensorVariable | tuple[pytensor.graph.basic.Variable, ...]) TensorVariable [source]#
Broadcast an array to a new shape.
- Parameters:
array – The array to broadcast.
shape – The shape of the desired array.
- Returns:
A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.
- Return type:
broadcast
- pytensor.tensor.extra_ops.compress(condition, x, axis=None)[source]#
Return selected slices of an array along given axis.
It returns the input tensor, but with selected slices along a given
axis
retained. If noaxis
is provided, the tensor is flattened. Corresponds tonumpy.compress
New in version 0.7.
- Parameters:
condition – One dimensional array of non-zero and zero values corresponding to indices of slices along a selected axis.
x – Input data, tensor variable.
axis – The axis along which to slice.
- Return type:
x
with selected slices.
- pytensor.tensor.extra_ops.cumprod(x, axis=None)[source]#
Return the cumulative product of the elements along a given
axis
.This wraps
numpy.cumprod
.- Parameters:
x – Input tensor variable.
axis – The axis along which the cumulative product is computed. The default (None) is to compute the
cumprod
over the flattened array.
New in version 0.7.
- pytensor.tensor.extra_ops.cumsum(x, axis=None)[source]#
Return the cumulative sum of the elements along a given
axis
.This wraps
numpy.cumsum
.- Parameters:
x – Input tensor variable.
axis – The axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
New in version 0.7.
- pytensor.tensor.extra_ops.diff(x, n=1, axis=-1)[source]#
Calculate the
n
-th order discrete difference along the givenaxis
.The first order difference is given by
out[i] = a[i + 1] - a[i]
along the givenaxis
, higher order differences are calculated by usingdiff
recursively. This is heavily inspired bynumpy.diff
.- Parameters:
x – Input tensor variable.
n – The number of times values are differenced, default is 1.
axis – The axis along which the difference is taken, default is the last axis.
New in version 0.6.
- pytensor.tensor.extra_ops.fill_diagonal(a, val)[source]#
Returns a copy of an array with all elements of the main diagonal set to a specified scalar value.
New in version 0.6.
- Parameters:
a – Rectangular array of at least two dimensions.
val – Scalar value to fill the diagonal whose type must be compatible with that of array
a
(i.e.val
cannot be viewed as an upcast ofa
).
- Returns:
array – An array identical to
a
except that its main diagonal is filled with scalarval
. (For an arraya
witha.ndim >= 2
, the main diagonal is the list of locationsa[i, i, ..., i]
(i.e. with indices all identical).)Support rectangular matrix and tensor with more than two dimensions
if the later have all dimensions are equals.
- pytensor.tensor.extra_ops.fill_diagonal_offset(a, val, offset)[source]#
Returns a copy of an array with all elements of the main diagonal set to a specified scalar value.
- Parameters:
a – Rectangular array of two dimensions.
val – Scalar value to fill the diagonal whose type must be compatible with that of array
a
(i.e.val
cannot be viewed as an upcast ofa
).offset – Scalar value Offset of the diagonal from the main diagonal. Can be positive or negative integer.
- Returns:
An array identical to
a
except that its offset diagonal is filled with scalarval
. The output is unwrapped.- Return type:
array
- pytensor.tensor.extra_ops.geomspace(start: Union[Variable, Sequence[Variable], ArrayLike], stop: Union[Variable, Sequence[Variable], ArrayLike], num: int = 50, base: float = 10.0, endpoint: bool = True, dtype: str | None = None, axis: int = 0, end: Optional[Union[Variable, Sequence[Variable], ArrayLike]] = None, steps: Optional[Union[Variable, Sequence[Variable], ArrayLike]] = None) TensorVariable [source]#
Return numbers spaced evenly on a log scale (a geometric progression).
This is similar to logspace, but with endpoints specified directly. Each output sample is a constant multiple of the previous.
- Parameters:
samples (Returns num evenly spaced) –
[start (calculated over the interval) –
stop]. –
excluded. (The endpoint of the interval can optionally be) –
start (int, float, or TensorVariable) – The starting value of the sequence.
stop (int, float or TensorVariable) – The end value of the sequence, unless
endpoint
is set to False. In that case, the sequence consists of all but the last ofnum + 1
evenly spaced samples, such thatstop
is excluded.num (int) – Number of samples to generate. Must be non-negative.
base (float) – The base of the log space.
endpoint (bool) – Whether to include the endpoint in the range.
dtype (str, optional) – dtype of the output tensor(s). If None, the dtype is inferred from that of the values provided to the
start
andend
arguments.axis (int) – Axis along which to generate samples. Ignored if both
start
andend
have dimension 0. By default, axis=0 will insert the samples on a new left-most dimension. To insert samples on a right-most dimension, use axis=-1.end (int, float or TensorVariable) –
Warning
The “end” parameter is deprecated and will be removed in a future version. Use “stop” instead.
The end value of the sequence, unless
endpoint
is set to False. In that case, the sequence consists of all but the last ofnum + 1
evenly spaced samples, such thatend
is excluded.steps (float, int, or TensorVariable) –
Warning
The “steps” parameter is deprecated and will be removed in a future version. Use “num” instead.
Number of samples to generate. Must be non-negative
- Returns:
samples –
- Tensor containing
num
evenly-spaced (in log space) values between [start, stop]. The range is inclusive if endpoint
is True.
- Tensor containing
- Return type:
- pytensor.tensor.extra_ops.linspace(start: Union[Variable, Sequence[Variable], ArrayLike], stop: Union[Variable, Sequence[Variable], ArrayLike], num: Union[Variable, Sequence[Variable], ArrayLike] = 50, endpoint: bool = True, retstep: bool = False, dtype: str | None = None, axis: int = 0, end: Optional[Union[Variable, Sequence[Variable], ArrayLike]] = None, steps: Optional[Union[Variable, Sequence[Variable], ArrayLike]] = None) pytensor.tensor.variable.TensorVariable | tuple[pytensor.tensor.variable.TensorVariable, pytensor.tensor.variable.TensorVariable] [source]#
Return evenly spaced numbers over a specified interval.
Returns
num
evenly spaced samples, calculated over the interval [start
,stop
].The endpoint of the interval can optionally be excluded.
- Parameters:
start (int, float, or TensorVariable) – The starting value of the sequence.
stop (int, float or TensorVariable) – The end value of the sequence, unless
endpoint
is set to False. In that case, the sequence consists of all but the last ofnum + 1
evenly spaced samples, such thatstop
is excluded.num (int) – Number of samples to generate. Must be non-negative.
endpoint (bool) – Whether to include the endpoint in the range.
retstep (bool) – If true, returns both the samples and an array of steps between samples.
dtype (str, optional) – dtype of the output tensor(s). If None, the dtype is inferred from that of the values provided to the
start
andend
arguments.axis (int) – Axis along which to generate samples. Ignored if both
start
andend
have dimension 0. By default, axis=0 will insert the samples on a new left-most dimension. To insert samples on a right-most dimension, use axis=-1.end (int, float or TensorVariable) –
Warning
The “end” parameter is deprecated and will be removed in a future version. Use “stop” instead.
The end value of the sequence, unless
endpoint
is set to False. In that case, the sequence consists of all but the last ofnum + 1
evenly spaced samples, such thatend
is excluded.steps (float, int, or TensorVariable) –
Warning
The “steps” parameter is deprecated and will be removed in a future version. Use “num” instead.
Number of samples to generate. Must be non-negative
- Returns:
samples (TensorVariable) – Tensor containing
num
evenly-spaced values between [start, stop]. The range is inclusive ifendpoint
is True.step (TensorVariable) – Tensor containing the spacing between samples. Only returned if
retstep
is True.
- pytensor.tensor.extra_ops.logspace(start: Union[Variable, Sequence[Variable], ArrayLike], stop: Union[Variable, Sequence[Variable], ArrayLike], num: int = 50, base: float = 10.0, endpoint: bool = True, dtype: str | None = None, axis: int = 0, end: Optional[Union[Variable, Sequence[Variable], ArrayLike]] = None, steps: Optional[Union[Variable, Sequence[Variable], ArrayLike]] = None) TensorVariable [source]#
Return numbers spaced evenly on a log scale.
- In linear space, the sequence starts at
base ** start
(base to the power of start) and ends withbase ** stop
(see
endpoint
below).
- Parameters:
start (int, float, or TensorVariable) –
base ** start
is the starting value of the sequencestop (int, float or TensorVariable) –
base ** stop
is the endpoint of the sequence, unlessendopoint
is set to False. In that case,num + 1
values are spaced over the interval in log-space, and the firstnum
are returned.num (int, default = 50) – Number of samples to generate.
base (float, default = 10.0) –
- The base of the log space. The step size between the elements in
log(samples) / log(base)
(or
log_base(samples)
is uniform.
- The base of the log space. The step size between the elements in
endpoint (bool) – Whether to include the endpoint in the range.
dtype (str, optional) – dtype of the output tensor(s). If None, the dtype is inferred from that of the values provided to the
start
andstop
arguments.axis (int) – Axis along which to generate samples. Ignored if both
start
andend
have dimension 0. By default, axis=0 will insert the samples on a new left-most dimension. To insert samples on a right-most dimension, use axis=-1.end (int float or TensorVariable) –
Warning
The “end” parameter is deprecated and will be removed in a future version. Use “stop” instead.
The end value of the sequence, unless
endpoint
is set to False. In that case, the sequence consists of all but the last ofnum + 1
evenly spaced samples, such thatend
is excluded.steps (int or TensorVariable) –
Warning
The “steps” parameter is deprecated and will be removed in a future version. Use “num” instead.
Number of samples to generate. Must be non-negative
- Returns:
samples – Tensor containing
num
evenly-spaced (in log-pace) values between [start, stop]. The range is inclusive ifendpoint
is True.- Return type:
- In linear space, the sequence starts at
- pytensor.tensor.extra_ops.ravel_multi_index(multi_index, dims, mode='raise', order='C')[source]#
Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.
- Parameters:
multi_index (tuple of PyTensor or NumPy arrays) – A tuple of integer arrays, one array for each dimension.
dims (tuple of ints) – The shape of array into which the indices from
multi_index
apply.mode ({'raise', 'wrap', 'clip'}, optional) – Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index. * ‘raise’ – raise an error (default) * ‘wrap’ – wrap around * ‘clip’ – clip to the range In ‘clip’ mode, a negative index which would normally wrap will clip to 0 instead.
order ({'C', 'F'}, optional) – Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.
- Returns:
raveled_indices – An array of indices into the flattened version of an array of dimensions
dims
.- Return type:
See also
- pytensor.tensor.extra_ops.repeat(x, repeats, axis=None)[source]#
Repeat elements of an array.
It returns an array which has the same shape as
x
, except along the givenaxis
. Theaxis
parameter is used to specify the axis along which values are repeated. By default, a flattened version ofx
is used.The number of repetitions for each element is
repeats
.repeats
is broadcasted to fit the length of the givenaxis
.- Parameters:
x – Input data, tensor variable.
repeats – int, scalar or tensor variable
axis (int, optional) –
See also
tensor.tile
,
- pytensor.tensor.extra_ops.searchsorted(x, v, side='left', sorter=None)[source]#
Find indices where elements should be inserted to maintain order.
This wraps
numpy.searchsorted
. Find the indices into a sorted arrayx
such that, if the corresponding elements inv
were inserted before the indices, the order ofx
would be preserved.- Parameters:
x (1-D tensor (array-like)) – Input array. If
sorter
isNone
, then it must be sorted in ascending order, otherwisesorter
must be an array of indices which sorts it.v (tensor (array-like)) – Contains the values to be inserted into
x
.side ({'left', 'right'}, optional.) – If
'left'
(default), the index of the first suitable location found is given. If'right'
, return the last such index. If there is no suitable index, return either 0 or N (where N is the length ofx
).sorter (1-D tensor of integers (array-like), optional) – Contains indices that sort array
x
into ascending order. They are typically the result of argsort.
- Returns:
indices – Array of insertion points with the same shape as
v
.- Return type:
tensor of integers (int64)
See also
Notes
Binary search is used to find the required insertion points.
This Op is working only on CPU currently.
Examples
>>> from pytensor import tensor as pt >>> from pytensor.tensor import extra_ops >>> x = pt.dvector("x") >>> idx = x.searchsorted(3) >>> idx.eval({x: [1, 2, 3, 4, 5]}) array(2) >>> extra_ops.searchsorted([1, 2, 3, 4, 5], 3).eval() array(2) >>> extra_ops.searchsorted([1, 2, 3, 4, 5], 3, side="right").eval() array(3) >>> extra_ops.searchsorted([1, 2, 3, 4, 5], [-10, 10, 2, 3]).eval() array([0, 5, 1, 2])
New in version 0.9.
- pytensor.tensor.extra_ops.squeeze(x, axis=None)[source]#
Remove broadcastable (length 1) dimensions from the shape of an array.
It returns the input array, but with the broadcastable dimensions removed. This is always
x
itself or a view intox
.New in version 0.6.
- Parameters:
x – Input data, tensor variable.
axis (None or int or tuple of ints, optional) – Selects a subset of broadcastable dimensions to be removed. If a non broadcastable dimension is selected, an error is raised. If
axis
isNone
, all broadcastable dimensions will be removed.
Notes
- The behavior can differ from that of NumPy in two ways:
1. If an axis is chosen for a dimension that is not known to be broadcastable an error is raised, even if this dimension would be broadcastable when the variable is evaluated. 2. Similarly, if
axis
isNone
, only dimensions known to be broadcastable will be removed, even if there are more dimensions that happen to be broadcastable when the variable is evaluated.
- Return type:
x
withoutaxis
dimensions.
- pytensor.tensor.extra_ops.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)[source]#
Find the unique elements of an array.
Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:
the indices of the input array that give the unique values
the indices of the unique array that reconstruct the input array
the number of times each unique value comes up in the input array
- pytensor.tensor.extra_ops.unravel_index(indices, dims, order='C')[source]#
Converts a flat index or array of flat indices into a tuple of coordinate arrays.
- Parameters:
indices (PyTensor or NumPy array) – An integer array whose elements are indices into the flattened version of an array of dimensions
dims
.dims (tuple of ints) – The shape of the array to use for unraveling
indices
.order ({'C', 'F'}, optional) – Determines whether the indices should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order.
- Returns:
unraveled_coords – Each array in the tuple has the same shape as the
indices
array.- Return type:
tuple of ndarray
See also