mygrad.Tensor.astype#

Tensor.astype(dtype: DTypeLikeReals, casting='unsafe', copy: bool = True, *, constant: bool | None = None) Tensor[source]#

Copy of the tensor with the specified dtype.

The resulting tensor is not involved in any computational graph and has no gradient associated with it.

This docstring was adapted from that of ndarray.astype.

Parameters:
dtypeUnion[type, str]

The real-valued numeric data type. This can be a numpy dtype or a corresponding string identifier.

castingLiteral[‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’]
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
  • ‘no’ means the data types should not be cast at all.

  • ‘equiv’ means only byte-order changes are allowed.

  • ‘safe’ means only casts which can preserve values are allowed.

  • ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.

  • ‘unsafe’ means any data conversions may be done.

copybool, optional (default=True)

By default, astype always returns a newly allocated array. If this is set to false, and the dtype and constant requirements are satisfied, the input tensor is returned instead of a copy.

constantOptional[bool]

If specified, determines if the returned tensor is a constant. Otherwise this argument is inferred from the original tensor.

Returns:
Tensor

The resulting tensor with the specified data type.

References

[1].. Retrieved from: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.html

Examples

>>> import mygrad as mg
>>> import numpy as np
>>> x = mg.arange(10); x
Tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Using a string to specify the data type:

>>> x.astype("float32")
Tensor([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)

Specifying a numpy data type object, and specifying that the tensor is to be treated as a constant:

>>> x.astype(np.int8, constant=True)
Tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int8)