【发布时间】:2021-08-27 13:52:37
【问题描述】:
假设我有以下张量:y = torch.randint(0, 3, (10,))。您将如何计算其中的 0 和 1 和 2?
我能想到的唯一方法是使用collections.Counter(y),但想知道是否有更“pytorch”的方式来做到这一点。例如,一个用例是构建预测的混淆矩阵。
【问题讨论】:
标签: pytorch
假设我有以下张量:y = torch.randint(0, 3, (10,))。您将如何计算其中的 0 和 1 和 2?
我能想到的唯一方法是使用collections.Counter(y),但想知道是否有更“pytorch”的方式来做到这一点。例如,一个用例是构建预测的混淆矩阵。
【问题讨论】:
标签: pytorch
您可以将torch.unique 与return_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]))
【讨论】: