mygrad.asarray#

mygrad.asarray(a: ArrayLike, dtype: DTypeLike | None = None, order: str | None = None) ndarray[source]#

Convert the input to an array.

This docstring is adapted from that of numpy.asarray

Parameters:
aarray_like

Input data, in any form - including a mygrad tensor - that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.

dtypedata-type, optional

By default, the data-type is inferred from the input data.

order{‘C’, ‘F’}, optional

Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’.

Returns:
outndarray

Array interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned.

Examples

Convert a list into an array:

>>> import mygrad as mg
>>> a = [1, 2]
>>> mg.asarray(a)
array([1, 2])

Convert a tensor into an array. No copy of the underlying numpy array is created:

>>> t = mg.Tensor([1, 2.])
>>> mg.asarray(t)
array([1., 2.])
>>> t.data is np.asarray(t))
True

Existing arrays are not copied:

>>> a = np.array([1, 2])
>>> mg.asarray(a) is a
True

If dtype is set, array is copied only if dtype does not match:

>>> a = np.array([1, 2], dtype=np.float32)
>>> mg.asarray(a, dtype=np.float32) is a
True
>>> mg.asarray(a, dtype=np.float64) is a
False

Contrary to asanyarray, ndarray subclasses are not passed through:

>>> issubclass(np.recarray, np.ndarray)
True
>>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
>>> mg.asarray(a) is a
False
>>> np.asanyarray(a) is a
True