英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论