温馨提示×

pytorch怎么统计元素出现次数

小亿
98
2024-03-28 14:37:11
栏目: 深度学习

在PyTorch中,可以使用torch.unique函数来统计元素出现的次数。以下是一个示例代码:

import torch

# 创建一个包含重复元素的张量
x = torch.tensor([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])

# 使用torch.unique函数来获取唯一元素和它们出现的次数
unique_elements, counts = torch.unique(x, return_counts=True)

# 打印结果
for i in range(len(unique_elements)):
    print(f"元素 {unique_elements[i]} 出现了 {counts[i]} 次")

运行以上代码,将得到输出:

元素 1 出现了 1 次
元素 2 出现了 2 次
元素 3 出现了 3 次
元素 4 出现了 4 次

0