pytorch张量更改维度为相邻值

发布于 2025-01-31 11:32:22 字数 381 浏览 1 评论 0 原文

我的目标是计算张量 x 的所有相邻唯一值。
假设我的张量是( x 看起来像一个列表,但它是pytorch张量)

x = [1,2,1,2,4,5]

我希望我的输出是:

[1,2] = 2
[2,1] = 1
[2,4] = 1
[4,5] = 1

我考虑更改张量的尺寸看起来像:

x = [[1,2],[2,1],[1,2],[2,4],[4,5]]

使用 tensor .View ,但找不到适用于任何长度张量的解决方案。 有什么想法是否是最好的方法?有内置功能吗?

My objective it to count all adjacent unique values of a tensor x.
Say my tensor is (x looks like a list but it is a pytorch tensor)

x = [1,2,1,2,4,5]

I would want my output to be:

[1,2] = 2
[2,1] = 1
[2,4] = 1
[4,5] = 1

I thought about changing the dimensionality of the tensor to look like:

x = [[1,2],[2,1],[1,2],[2,4],[4,5]]

using tensor.view but couldn't find a solution that works for a tensor of any length.
Any ideas if this is even the best way to go about this? is there some built-in function?

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

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

发布评论

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

评论(1

疏忽 2025-02-07 11:32:22

AS @ihdv 显示,您可以使用 x torch.stack.stack pytorch.org/docs/stable/generated/torch.vstack.html“ rel =” nofollow noreferrer“> torch.vstack.vstack ,以获取带有重叠窗口的成对张量。

>>> p = torch.vstack((x[:-1], x[1:]))
tensor([[1., 2., 1., 2., 4.],
        [2., 1., 2., 4., 5.]])

然后,您可以应用在其上获取统计信息:

>>> p.unique(dim=1, return_counts=True)
(tensor([[1., 2., 2., 4.],
         [2., 1., 4., 5.]]), tensor([2, 1, 1, 1]))

As @ihdv showed, you can stack shifted views of x with torch.stack or torch.vstack in order to get a tensor of pairs with overlapping windows.

>>> p = torch.vstack((x[:-1], x[1:]))
tensor([[1., 2., 1., 2., 4.],
        [2., 1., 2., 4., 5.]])

Then you can apply torch.unique on it to get the statistics:

>>> p.unique(dim=1, return_counts=True)
(tensor([[1., 2., 2., 4.],
         [2., 1., 4., 5.]]), tensor([2, 1, 1, 1]))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文