mindspore.ops.Cast

View Source On Gitee
class mindspore.ops.Cast[source]

Returns a tensor with the new specified data type.

Note

When converting complex numbers to boolean type, the imaginary part of the complex number is not taken into account. As long as the real part is non-zero, it returns True; otherwise, it returns False.

Inputs:
  • input_x (Union[Tensor, Number]) - The shape of tensor is \((x_1, x_2, ..., x_R)\). The tensor to be cast.

  • type (dtype.Number) - The valid data type of the output tensor. Only constant value is allowed.

Outputs:

Tensor, the shape of tensor is the same as input_x, \((x_1, x_2, ..., x_R)\).

Raises
  • TypeError – If input_x is neither Tensor nor Number.

  • TypeError – If type is not a Number.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor, ops
>>> input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
>>> input_x = Tensor(input_np)
>>> type_dst = mindspore.int32
>>> cast = ops.Cast()
>>> output = cast(input_x, type_dst)
>>> print(output.dtype)
Int32
>>> print(output.shape)
(2, 3, 4, 5)