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

如何将二维列表中相同向量编码为同一值?(PyTorch/Numpy实现)

用Numpy和PyTorch实现二维数组中相同行的标记

Numpy实现方法

直接使用np.unique()函数,指定axis=0以整行作为单位判断是否重复,同时设置return_inverse=True,该参数会返回原数组每行在唯一行集合中的索引,恰好就是需要的标记结果。

代码示例:

import numpy as np

a = np.array([[0,0], [0,0], [0,0], [0,2], [0,2], [1,0]])
_, labels = np.unique(a, axis=0, return_inverse=True)
print(labels)  # 输出: [0 0 0 1 1 2]

PyTorch实现方法

PyTorch的torch.unique()函数支持相同逻辑,指定dim=0按行处理重复项,return_inverse=True返回对应索引数组。

代码示例:

import torch

a = torch.tensor([[0,0], [0,0], [0,0], [0,2], [0,2], [1,0]])
_, labels = torch.unique(a, dim=0, return_inverse=True)
print(labels.numpy())  # 输出: [0 0 0 1 1 2]

内容的提问来源于stack exchange,提问作者zihao jiao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:12:42