【问题标题】:How can I count the number of 1's and 0's in the second dimension of a PyTorch Tensor?如何计算 PyTorch 张量的第二维中 1 和 0 的数量?
【发布时间】:2020-04-01 03:15:56
【问题描述】:

我有一个大小为:torch.Size([64, 2941]) 的张量,即 64 批 2941 个元素。

在所有 64 个批次中,我想计算张量的第二维中 1 和 0 的总数,一直到第 2941 个,以便将这些计数作为大小为 torch.Size([2941]) 的张量

p>

我该怎么做?

【问题讨论】:

    标签: python pytorch tensor


    【解决方案1】:

    你可以总结它们:

    import torch
    torch.manual_seed(2020)
    
    # x is a fake data, it should be your tensor with 64x2941
    x = (torch.rand((3,4)) > 0.5).to(torch.int32)
    print(x)
    # tensor([[0, 0, 1, 0],
    #         [0, 0, 1, 1],
    #         [0, 1, 1, 1]], dtype=torch.int32)
    
    ones = (x == 1.).sum(dim=0)
    print(ones)
    # tensor([0, 1, 3, 2])
    

    如果x 是二进制的,你可以通过简单的减法得到零的个数:

    zeros = x.shape[1] - ones
    

    【讨论】:

      猜你喜欢
      • 2019-09-15
      • 2020-08-26
      • 2020-12-18
      • 2020-09-26
      • 2015-04-16
      • 2018-06-08
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      相关资源
      最近更新 更多