mindspore.Tensor.flatten

Tensor.flatten(start_dim=0, end_dim=- 1) Tensor

Flatten a tensor along dimensions from start_dim to end_dim.

Parameters
  • start_dim (int, optional) – The first dimension to flatten. Default: 0 .

  • end_dim (int, optional) – The last dimension to flatten. Default: -1 .

Returns

Tensor. If no dimensions are flattened, returns the original self, otherwise return the flattened Tensor. If self is a 0-dimensional Tensor, a 1-dimensional Tensor will be returned.

Raises
  • TypeError – If start_dim or end_dim is not int.

  • ValueError – If start_dim is greater than end_dim after canonicalized.

  • ValueError – If start_dim or end_dim is not in range of [-self.dim, self.dim-1].

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.ones(shape=[1, 2, 3, 4]), mindspore.float32)
>>> output = input_x.flatten(0, -1)
>>> print(output.shape)
(24,)
Tensor.flatten(order='C', *, start_dim=0, end_dim=- 1) Tensor

Flatten a tensor along dimensions from start_dim to start_dim.

Parameters

order (str, optional) – Only 'C' and 'F' are supported. 'C' means to flatten in row-major (C-style) order. 'F' means to flatten in column-major (Fortran-style) order. Default: 'C' .

Keyword Arguments
  • start_dim (int, optional) – The first dimension to flatten. Default: 0 .

  • end_dim (int, optional) – The last dimension to flatten. Default: -1 .

Returns

Tensor. If no dimensions are flattened, returns the original self, otherwise return the flattened Tensor. If self is a 0-dimensional Tensor, a 1-dimensional Tensor will be returned.

Raises
  • TypeError – If order is not string type.

  • ValueError – If order is string type, but not 'C' or 'F'.

  • TypeError – If start_dim or end_dim is not int.

  • ValueError – If start_dim is greater than end_dim after canonicalized.

  • ValueError – If start_dim or end_dim is not in range of [-self.dim, self.dim-1].

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.ones(shape=[1, 2, 3, 4]), mindspore.float32)
>>> output = input_x.flatten(order='C')
>>> print(output.shape)
(24,)