mindspore.nn.Flatten

class mindspore.nn.Flatten(start_dim=1, end_dim=- 1)[source]

Flatten the input Tensor along dimensions from start_dim to end_dim.

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

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

Inputs:
  • x (Tensor) - The input Tensor to be flattened.

Outputs:

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

Raises
  • TypeError – If x is not a Tensor.

  • 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 [-x.dim, x.dim-1]. For example, the default values are used for the args and the input is a 0-dimensional or 1-dimensional Tensor.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore
>>> from mindspore import Tensor, nn
>>> import numpy as np
>>> x = Tensor(np.array([[[1.2, 1.2], [2.1, 2.1]], [[2.2, 2.2], [3.2, 3.2]]]), mindspore.float32)
>>> net = nn.Flatten()
>>> output = net(x)
>>> print(output)
[[1.2 1.2 2.1 2.1]
 [2.2 2.2 3.2 3.2]]
>>> print(f"before flatten the x shape is {x.shape}")
before flatten the x shape is  (2, 2, 2)
>>> print(f"after flatten the output shape is {output.shape}")
after flatten the output shape is (2, 4)