mygrad.astensor(t: ArrayLike, dtype: Optional[DTypeLikeReals] = None, *, constant: Optional[bool] = None) Tensor[source]#

Convert the input to a tensor.

A tensor t is returned unchanged - its gradient and computational graph state preserved - if dtype and constant are compatible. A copy of the underlying numpy array is created only if dtype is incompatible or if a non-constant tensor is being created from a constant.


Input data, in any form that can be converted to a tensor. 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.


By default, constant is inferred from t if t is a tensor, otherwise it defaults to False.

Defaults to False for float-type data. Defaults to True for integer-type data.

Integer-type tensors must be constant.


Tensor interpretation of a. No copy is performed if the input is already a tensor with matching dtype and constant-flag.


Convert a list into an array:

>>> import mygrad as mg
>>> import numpy as np
>>> t = [1, 2]
>>> mg.astensor(t)
Tensor([1, 2])

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

>>> a = np.array([1.0, 2.0])
>>> mg.astensor(a)
Tensor([1., 2.])
>>> a is mg.astensor(a).data

Existing tensors are not copied and their gradients and computational graphs are preserved:

>>> t1 = 2 * mg.tensor([1, 2])
>>> t2 = mg.astensor(t1)
>>> t1 is t2
>>> t1.creator is t2.creator

If dtype is set, a new tensor is created - with copied data - only if dtype does not match:

>>> t = mg.Tensor([1, 2], dtype=np.float32)
>>> mg.astensor(t, dtype=np.float32) is t
>>> mg.astensor(t, dtype=np.float64) is t

Otherwise, if constant is set, a new tensor is created (with no copy of the underlying data) only if constant doesn’t match.

>>> t1 = mg.tensor([1, 2], constant=False)
>>> mg.astensor(t1, constant=False) is t
>>> mg.astensor(t1, constant=True) is t1
>>> mg.astensor(t1, constant=True).data is