是否存在PyTorch内置方法返回1D张量中出现次数最多的元素?
Answer
Yes, PyTorch has a built-in method that perfectly fits your needs: torch.mode().
Here's how it aligns with your requirements:
- For a 1D input tensor, it returns the most frequently occurring element.
- If multiple elements have the same highest occurrence count (a tie), it automatically returns the smallest value among those elements—exactly what you need for your second example.
Let’s test it with your sample inputs:
Example 1: Single mode
import torch tensor1 = torch.tensor([2,2,2,3,4,5]) mode_result = tensor1.mode() print(mode_result.values.item()) # Output: 2
Example 2: Tie between modes
tensor2 = torch.tensor([1,1,2,2,4,5]) mode_result = tensor2.mode() print(mode_result.values.item()) # Output: 1
A quick note: torch.mode() returns a named tuple containing both the mode value(s) and their indices in the original tensor. For a 1D input, accessing .values.item() gives you the scalar mode value directly.
Content of the question originates from Stack Exchange, asked by Train Heartnet
相关产品推荐
相关产品推荐

