mygrad.astensor#
- mygrad.astensor(t: ArrayLike, dtype: DTypeLikeReals | None = None, *, constant: bool | None = 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.
- Parameters:
- tarray_like
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.
- constantOptional[bool]
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 toTrue
for integer-type data.Integer-type tensors must be constant.
- Returns:
- outTensor
Tensor interpretation of a. No copy is performed if the input is already a tensor with matching dtype and constant-flag.
Examples
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 True
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 True >>> t1.creator is t2.creator True
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 True >>> mg.astensor(t, dtype=np.float64) is t False
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 True >>> mg.astensor(t1, constant=True) is t1 False >>> mg.astensor(t1, constant=True).data is t1.data True