减去torch Tensor中每对元素的差 efficiently

huangapple go评论55阅读模式
英文:

Subtract the elements of every possible pair of a torch Tensor efficiently

问题

我有一个庞大的Torch Tensor,我正在寻找一种高效的方法来减去该Tensor的每对元素。当然,我可以使用两个嵌套的for循环,但这不会很高效。

例如,给定

[1, 2, 3, 4]

我想要的输出是

[1-2, 1-3, 1-4, 2-3, 2-4, 3-4]
英文:

I have a huge torch Tensor and I'm looking for an efficient approach to subtract the elements of every pair of that Tensor.
Of course I could use two nested for but it wouldn't be efficient.

For example giving

[1, 2, 3, 4]

The output I want is

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

答案1

得分: 1

你可以轻松地做到这一点:

>>> x = torch.tensor([1, 2, 3, 4])
>>> x[:, None] - x[None, :]
tensor([[ 0, -1, -2, -3],
        [ 1,  0, -1, -2],
        [ 2,  1,  0, -1],
        [ 3,  2,  1,  0]])

更多细节请参考这里

英文:

You can do this easily:

>>> x = torch.tensor([1, 2, 3, 4])
>>> x[:, None] - x[None, :]
tensor([[ 0, -1, -2, -3],
        [ 1,  0, -1, -2],
        [ 2,  1,  0, -1],
        [ 3,  2,  1,  0]])

see more details here.

huangapple
  • 本文由 发表于 2023年2月9日 03:11:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定