squeeze

paddle. squeeze ( x, axis=None, name=None ) [源代码]

该OP会删除输入Tensor的Shape中尺寸为1的维度。如果指定了axis,则会删除axis中指定的尺寸为1的维度。如果没有指定axis,那么所有等于1的维度都会被删除。

请注意,在动态图模式下,输出Tensor将与输入Tensor共享数据,并且没有Tensor数据拷贝的过程。 如果不希望输入与输出共享数据,请使用 Tensor.clone ,例如 squeeze_clone_x = x.squeeze().clone() 。

  1. Case 1:
  2. Input:
  3. x.shape = [1, 3, 1, 5] # If axis is not provided, all dims equal of size 1 will be removed.
  4. axis = None
  5. Output:
  6. out.shape = [3, 5]
  7. Case 2:
  8. Input:
  9. x.shape = [1, 3, 1, 5] # If axis is provided, it will remove the dimension(s) by given axis that of size 1.
  10. axis = 0
  11. Output:
  12. out.shape = [3, 1, 5]
  13. Case 3:
  14. Input:
  15. x.shape = [1, 3, 1, 5] # If the dimension of one given axis (3) is not of size 1, the dimension remain unchanged.
  16. axis = [0, 2, 3]
  17. Output:
  18. out.shape = [3, 5]
  19. Case 4:
  20. Input:
  21. x.shape = [1, 3, 1, 5] # If axis is negative, axis = axis + ndim (number of dimensions in x).
  22. axis = [-2]
  23. Output:
  24. out.shape = [1, 3, 5]

参数

  • x (Tensor) - 输入的 Tensor ,数据类型为:float32、float64、bool、int8、int32、int64。

  • axis (int|list|tuple, 可选) - 输入一个或一列整数,代表要压缩的轴。axis的范围: [−ndim(x), ndim(x))] 。 如果axis为负数, 则axis=axis+ndim(x) 。默认为None,表示对所有尺寸为1的维度进行压缩。

  • name (str, 可选) - 操作的名称(可选,默认值为None)。更多信息请参见 Name

返回:对维度进行压缩后的Tensor,数据类型与输入Tensor一致。

代码示例

  1. import paddle
  2. x = paddle.rand([5, 1, 10])
  3. output = paddle.squeeze(x, axis=1)
  4. print(x.shape) # [5, 1, 10]
  5. print(output.shape) # [5, 10]
  6. # 在动态图模式下,输出output与输入x共享数据
  7. x[0, 0, 0] = 10.
  8. print(output[0, 0]) # [10.]

使用本API的教程文档