如何根据2-D张量的值将3-D张量设置为0

发布于 2025-02-11 08:09:21 字数 475 浏览 1 评论 0 原文

假设我有一个3-D张量 P 形状(B,N,D)和2-D Tensor q Q 形状(( b,n),其中 q 中的值小于 d 。我想在 p 中将一些值设置为 0 使用 Q 的索引:

例如,

P = torch.randn(2,3,6)
Q = torch.tensor([[0,3,4], [2,1,3]])

我如何设置 p [0 ,0,0] = 0; p [0,1,3] = 0; p [0,2,4] = 0; p [1,0,2] = 0; p [1,1,1] = 0; p [1,2,3] = 0 使用 q 并将其他值保留在 p 不变的中?

Suppose I have a 3-d tensor P shaped (B, N, d) and a 2-d tensor Q shaped (B,N), where values in Q are smaller than d. I want to set some values in P to 0 using the indices from Q:

For instance,

P = torch.randn(2,3,6)
Q = torch.tensor([[0,3,4], [2,1,3]])

How can I set P[0,0,0]=0; P[0,1,3]=0; P[0,2,4]=0; P[1,0,2]=0; P[1,1,1]=0; P[1,2,3]=0 using Q and keep other values in P unchanged?

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

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

发布评论

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

评论(1

一瞬间的火花 2025-02-18 08:09:21

您要做的是:

P[i, j, Q[i, j]] = 0

这是 torch.tensor.scatter ,其效果是在指定的位置上放置任意价值。

我们首先需要输入和索引器具有匹配形状:

>>> Q_ = Q[...,None].expand_as(P)

并将散点功能应用于 dim = 2 ,并使用 hidden value 参数。 。

P.scatter(dim=2, index=Q_, value=0)
tensor([[[0, 2, 5, 4, 3, 7],
         [4, 1, 5, 0, 3, 8],
         [7, 8, 4, 3, 0, 1]],

        [[7, 1, 0, 1, 1, 3],
         [5, 0, 5, 3, 0, 5],
         [6, 3, 5, 0, 7, 2]]])

What you are looking to do is:

P[i, j, Q[i, j]] = 0

This is the perfect use case for torch.Tensor.scatter, which has the effect of placing an arbitrary value at designated positions.

We first need the input and indexer to have matching shapes:

>>> Q_ = Q[...,None].expand_as(P)

And apply the scatter function on dim=2, with the hidden value argument...

P.scatter(dim=2, index=Q_, value=0)
tensor([[[0, 2, 5, 4, 3, 7],
         [4, 1, 5, 0, 3, 8],
         [7, 8, 4, 3, 0, 1]],

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