【问题标题】:Count Unique elements in pytorch Tensor计算pytorch张量中的唯一元素
【发布时间】:2021-08-27 13:52:37
【问题描述】:

假设我有以下张量:y = torch.randint(0, 3, (10,))。您将如何计算其中的 0 和 1 和 2?

我能想到的唯一方法是使用collections.Counter(y),但想知道是否有更“pytorch”的方式来做到这一点。例如,一个用例是构建预测的混淆矩阵。

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    您可以将torch.uniquereturn_counts 选项一起使用:

    >>> x = torch.randint(0, 3, (10,))
    tensor([1, 1, 0, 2, 1, 0, 1, 1, 2, 1])
    
    >>> x.unique(return_counts=True)
    (tensor([0, 1, 2]), tensor([2, 6, 2]))
    

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 2015-04-18
      • 1970-01-01
      • 2021-08-30
      • 2021-03-04
      • 2022-11-25
      • 2021-09-14
      • 1970-01-01
      • 2020-07-06
      相关资源
      最近更新 更多