评价此页

torch.count_nonzero#

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

计算张量 input 中沿给定 dim 的非零值的数量。如果未指定 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])