Array#
- class brainpy.math.Array(value, dtype=None)[source]#
Multiple-dimensional array in BrainPy.
Compared to
jax.Array
,Array
has the following advantages:In-place updating is supported.
>>> import brainpy.math as bm >>> a = bm.asarray([1, 2, 3.]) >>> a[0] = 10.
Keep sharding constraints during computation.
More dense array operations with PyTorch syntax.
- addr(vec1, vec2, *, beta=1.0, alpha=1.0, out=None)[source]#
Performs the outer-product of vectors
vec1
andvec2
and adds it to the matrixinput
.Optional values beta and alpha are scaling factors on the outer product between vec1 and vec2 and the added matrix input respectively.
\[out = \beta \mathrm{input} + \alpha (\text{vec1} \bigtimes \text{vec2})\]- Parameters:
- Return type:
- argpartition(kth, axis=-1, kind='introselect', order=None)[source]#
Returns the indices that would partition this array.
- astype(dtype)[source]#
Copy of the array, cast to a specified type.
- Parameters:
dtype (str, dtype) – Typecode or data-type to which the array is cast.
- byteswap(inplace=False)[source]#
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.
- choose(choices, mode='raise')[source]#
Use an index array to construct a new array from a set of choices.
- clamp(min_value=None, max_value=None, *, out=None)[source]#
return the value between min_value and max_value, if min_value is None, then no lower bound, if max_value is None, then no upper bound.
- clamp_(min_value=None, max_value=None)[source]#
return the value between min_value and max_value, if min_value is None, then no lower bound, if max_value is None, then no upper bound.
- clip(min=None, max=None, out=None)[source]#
Return an array whose values are limited to [min, max]. One of max or min must be given.
- cumprod(axis=None, dtype=None)[source]#
Return the cumulative product of the elements along the given axis.
- cumsum(axis=None, dtype=None)[source]#
Return the cumulative sum of the elements along the given axis.
- property dtype#
Variable dtype.
- expand(*sizes)[source]#
Expand an array to a new shape.
- Parameters:
sizes (tuple or int) – The shape of the desired array. A single integer
i
is interpreted as(i,)
.- Returns:
expanded – A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a expanded array may refer to a single memory location.
- Return type:
- expand_dims(axis)[source]#
1. 如果axis类型为int: 返回一个在self基础上的第axis维度前插入一个维度Array, axis<0表示倒数第|axis|维度, 令n=len(self._value.shape),则axis的范围为[-(n+1),n]
2. 如果axis类型为Sequence[int]: 则返回依次扩展axis[i]的结果, 即self.expand_dims(axis)==self.expand_dims(axis[0]).expand_dims(axis[1])…expand_dims(axis[len(axis)-1])
- Return type:
If the type of axis is int:
Returns an Array of dimensions inserted before the axis dimension based on self,
The first | axis < 0 indicates the bottom axis | dimensions,
Set n=len(self._value.shape), then axis has the range [-(n+1),n]
If the type of axis is Sequence[int] :
Returns the result of extending axis[i] in sequence,
self.expand_dims(axis)==self.expand_dims(axis[0]).expand_dims(axis[1])… expand_dims(axis[len(axis)-1])
- log_normal_(mean=1, std=2)[source]#
Fills self tensor with numbers samples from the log-normal distribution parameterized by the given mean \(\mu\) and standard deviation \(\sigma\). Note that mean and std are the mean and standard deviation of the underlying normal distribution, and not of the returned distribution:
\[f(x)=\frac{1}{x \sigma \sqrt{2 \pi}} e^{-\frac{(\ln x-\mu)^2}{2 \sigma^2}}\]- Parameters:
mean – the mean value.
std – the standard deviation.
- mean(axis=None, dtype=None, keepdims=False, *args, **kwargs)[source]#
Returns the average of the array elements along given axis.
- normal_()[source]#
Fills self tensor with elements samples from the normal distribution parameterized by mean and std.
- prod(axis=None, dtype=None, keepdims=False, initial=1, where=True)[source]#
Return the product of the array elements over the given axis.
- put(indices, values)[source]#
Replaces specified elements of an array with given values.
- Parameters:
indices (array_like) – Target indices, interpreted as integers.
values (array_like) – Values to place in the array at target indices.
- searchsorted(v, side='left', sorter=None)[source]#
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.
Assuming that a is sorted:
side
returned index i satisfies
left
a[i-1] < v <= a[i]
right
a[i-1] <= v < a[i]
- Parameters:
v (array_like) – Values to insert into a.
side ({'left', 'right'}, optional) – If ‘left’, 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 of a).
sorter (1-D array_like, optional) – Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort.
- Returns:
indices – Array of insertion points with the same shape as v.
- Return type:
array of ints
- property shape#
Variable shape.
- sort(axis=-1, stable=True, order=None)[source]#
Sort an array in-place.
- Parameters:
axis (int, optional) – Axis along which to sort. Default is -1, which means sort along the last axis.
stable (bool, optional) – Whether to use a stable sorting algorithm. The default is True.
order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
- split(indices_or_sections, axis=0)[source]#
Split an array into multiple sub-arrays as views into
ary
.- Parameters:
indices_or_sections (int, 1-D array) –
If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.
If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example,
[2, 3]
would, foraxis=0
, result inary[:2]
ary[2:3]
ary[3:]
If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.
axis (int, optional) – The axis along which to split, default is 0.
- Returns:
sub-arrays – A list of sub-arrays as views into ary.
- Return type:
list of ndarrays
- std(axis=None, dtype=None, ddof=0, keepdims=False)[source]#
Compute the standard deviation along the specified axis.
Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.
- Parameters:
axis (None or int or tuple of ints, optional) – Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. If this is a tuple of ints, a standard deviation is performed over multiple axes, instead of a single axis or all the axes as before.
dtype (dtype, optional) – Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type.
ddof (int, optional) – Means Delta Degrees of Freedom. The divisor used in calculations is
N - ddof
, whereN
represents the number of elements. By default ddof is zero.keepdims (bool, optional) –
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the std method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
- Returns:
standard_deviation – If out is None, return a new array containing the standard deviation, otherwise return a reference to the output array.
- Return type:
ndarray, see dtype parameter above.
- sum(axis=None, dtype=None, keepdims=False, initial=0, where=True)[source]#
Return the sum of the array elements over the given axis.
- take(indices, axis=None, mode=None)[source]#
Return an array formed from the elements of a at the given indices.
- tile(reps)[source]#
Construct an array by repeating A the number of times given by reps.
If reps has length
d
, the result will have dimension ofmax(d, A.ndim)
.If
A.ndim < d
, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.If
A.ndim > d
, reps is promoted to A.ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).Note : Although tile may be used for broadcasting, it is strongly recommended to use numpy’s broadcasting operations and functions.
- Parameters:
reps (array_like) – The number of repetitions of A along each axis.
- Returns:
c – The tiled output array.
- Return type:
ndarray
- tobytes()[source]#
Construct Python bytes containing the raw data bytes in the array.
Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the
order
parameter.
- tolist()[source]#
Return the array as an
a.ndim
-levels deep nested list of Python scalars.Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the ~numpy.ndarray.item function.
If
a.ndim
is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar.
- transpose(*axes)[source]#
Returns a view of the array with axes transposed.
For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and
a.shape = (i[0], i[1], ... i[n-2], i[n-1])
, thena.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0])
.- Parameters:
axes (None, tuple of ints, or n ints) –
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means a’s i-th axis becomes a.transpose()’s j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form)
- Returns:
out – View of a, with axes suitably permuted.
- Return type:
ndarray
- var(axis=None, dtype=None, ddof=0, keepdims=False)[source]#
Returns the variance of the array elements, along given axis.
- view(*args, dtype=None)[source]#
New view of array with the same data.
This function is compatible with pytorch syntax.
Returns a new tensor with the same data as the
self
tensor but of a differentshape
.The returned tensor shares the same data and must have the same number of elements, but may have a different size. For a tensor to be viewed, the new view size must be compatible with its original size and stride, i.e., each new view dimension must either be a subspace of an original dimension, or only span across original dimensions \(d, d+1, \dots, d+k\) that satisfy the following contiguity-like condition that \(\forall i = d, \dots, d+k-1\),
\[\text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1]\]Otherwise, it will not be possible to view
self
tensor asshape
without copying it (e.g., viacontiguous()
). When it is unclear whether aview()
can be performed, it is advisable to usereshape()
, which returns a view if the shapes are compatible, and copies (equivalent to callingcontiguous()
) otherwise.- Parameters:
shape (int...) – the desired size
Example:
>>> x = brainpy.math.random.randn(4, 4) >>> x.size [4, 4] >>> y = x.view(16) >>> y.size [16] >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions >>> z.size [2, 8] >>> a = brainpy.math.random.randn(1, 2, 3, 4) >>> a.size [1, 2, 3, 4] >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension >>> b.size [1, 3, 2, 4] >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory >>> c.size [1, 3, 2, 4] >>> brainpy.math.equal(b, c) False
- view(dtype) Tensor [source]
Returns a new tensor with the same data as the
self
tensor but of a differentdtype
.If the element size of
dtype
is different than that ofself.dtype
, then the size of the last dimension of the output will be scaled proportionally. For instance, ifdtype
element size is twice that ofself.dtype
, then each pair of elements in the last dimension ofself
will be combined, and the size of the last dimension of the output will be half that ofself
. Ifdtype
element size is half that ofself.dtype
, then each element in the last dimension ofself
will be split in two, and the size of the last dimension of the output will be double that ofself
. For this to be possible, the following conditions must be true:self.dim()
must be greater than 0.self.stride(-1)
must be 1.
Additionally, if the element size of
dtype
is greater than that ofself.dtype
, the following conditions must be true as well:self.size(-1)
must be divisible by the ratio between the element sizes of the dtypes.self.storage_offset()
must be divisible by the ratio between the element sizes of the dtypes.The strides of all dimensions, except the last dimension, must be divisible by the ratio between the element sizes of the dtypes.
If any of the above conditions are not met, an error is thrown.
- Parameters:
dtype (
dtype
) – the desired dtype
Example:
>>> x = brainpy.math.random.randn(4, 4) >>> x Array([[ 0.9482, -0.0310, 1.4999, -0.5316], [-0.1520, 0.7472, 0.5617, -0.8649], [-2.4724, -0.0334, -0.2976, -0.8499], [-0.2109, 1.9913, -0.9607, -0.6123]]) >>> x.dtype brainpy.math.float32 >>> y = x.view(brainpy.math.int32) >>> y tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], [-1105482831, 1061112040, 1057999968, -1084397505], [-1071760287, -1123489973, -1097310419, -1084649136], [-1101533110, 1073668768, -1082790149, -1088634448]], dtype=brainpy.math.int32) >>> y[0, 0] = 1000000000 >>> x tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], [-0.1520, 0.7472, 0.5617, -0.8649], [-2.4724, -0.0334, -0.2976, -0.8499], [-0.2109, 1.9913, -0.9607, -0.6123]]) >>> x.view(brainpy.math.cfloat) tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], [-0.1520+0.7472j, 0.5617-0.8649j], [-2.4724-0.0334j, -0.2976-0.8499j], [-0.2109+1.9913j, -0.9607-0.6123j]]) >>> x.view(brainpy.math.cfloat).size [4, 2] >>> x.view(brainpy.math.uint8) tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, 8, 191], [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, 93, 191], [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, 89, 191], [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, 28, 191]], dtype=brainpy.math.uint8) >>> x.view(brainpy.math.uint8).size [4, 16]