生成一维张量作为2D张量行的独特索引(保持订单和原始索引)

发布于 2025-02-09 13:20:15 字数 603 浏览 1 评论 0原文

这个问题是

假设我们通过给出每个行,不同行的不同索引,从0行数-1 。

[[1,4],[1,3],[1,2]] -> [0,1,2]

但是,如果有相同的行,我们将重复索引,如下所示,“原始”索引为k-1,对于k -

[[1,4],[1,2],[1,2]] -> [0,1,1]

如果没有重复该行(如下面的第三行),其索引应为其原始索引,它是k-1k -th Row(例如2 for 2 for [1,4])。

[[1,3],[1,3],[1,4]] -> [0,0,2]

一个更长的例子:

[[1,2],[4,3],[1,4],[1,4],[4,3],[1,2],[5,6],[7,8]] -> [0,1,2,2,1,0,6,7]

如何在pytorch上实施它?

This question is an updated version of generate 1D tensor as unique index of rows of an 2D tensor

Let's say we transform a 2D tensor to a 1D tensor by giving each, different row a different index, from 0 to the number of rows - 1.

[[1,4],[1,3],[1,2]] -> [0,1,2]

But if there are same rows, we repeat the index, like this below, the "original" index is k-1 for the k-th row

[[1,4],[1,2],[1,2]] -> [0,1,1]

Also if there is no repeat for the row (like the third row below), its index should be its original index, which is k-1 for the k-th row (for example 2 for [1,4]).

[[1,3],[1,3],[1,4]] -> [0,0,2]

A longer example:

[[1,2],[4,3],[1,4],[1,4],[4,3],[1,2],[5,6],[7,8]] -> [0,1,2,2,1,0,6,7]

How to implement this on PyTorch?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你又不是我 2025-02-16 13:20:15

以下解决方案是矢量化的,但依赖于Numpy的unique函数。

>>> x = np.array([[1,2],[4,3],[1,4],[1,4],[4,3],[1,2],[5,6],[7,8]])
>>> _, index, inverse = np.unique(x, return_index=True, return_inverse=True, axis=0)
>>> index[inverse]
array([0, 1, 2, 2, 1, 0, 6, 7])

The following solution is vectorized, but relies on NumPy's unique function.

>>> x = np.array([[1,2],[4,3],[1,4],[1,4],[4,3],[1,2],[5,6],[7,8]])
>>> _, index, inverse = np.unique(x, return_index=True, return_inverse=True, axis=0)
>>> index[inverse]
array([0, 1, 2, 2, 1, 0, 6, 7])
审判长 2025-02-16 13:20:15

请参阅@michael的非矢量化解决方案,

 d = {}; torch.tensor([d.setdefault(tuple(i.tolist()), e) for e, i in enumerate(t4)]) 

另一个非矢量化解决方案是

t4_list = t4.tolist(); torch.tensor(list(map(lambda x: t4_list.index(x), t4)))

See the non-vectorized solution from @Michael

 d = {}; torch.tensor([d.setdefault(tuple(i.tolist()), e) for e, i in enumerate(t4)]) 

Another non-vectorized solution is

t4_list = t4.tolist(); torch.tensor(list(map(lambda x: t4_list.index(x), t4)))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文