評價此頁

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])