You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否存在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 20:27:44