评价此页

torch.count_nonzero#

torch.count_nonzero(input, dim=None) Tensor#

在给定的 dim 上计算张量 input 中的非零值数量。如果未指定 dim,则计算张量中的所有非零值。

参数
  • input (Tensor) – 输入张量。

  • dim (inttuple of ints, optional) – 要计算非零值的维度或维度的元组。

示例

>>> x = torch.zeros(3,3)
>>> x[torch.randn(3,3) > 0.5] = 1
>>> x
tensor([[0., 1., 1.],
        [0., 0., 0.],
        [0., 0., 1.]])
>>> torch.count_nonzero(x)
tensor(3)
>>> torch.count_nonzero(x, dim=0)
tensor([0, 1, 2])