pytorch张量 - 随机替换满足条件的值

发布于 2025-01-21 13:55:00 字数 429 浏览 4 评论 0 原文

我有一个pytorch张量尺寸的蒙版

torch.Size([8, 24, 24])

具有独特的值,

> torch.unique(mask, return_counts=True)
(tensor([0, 1, 2]), tensor([2093, 1054, 1461]))

我希望随机将2s的数量随机替换为0s,以使张量的唯一值和计数变成,

> torch.unique(mask, return_counts=True)
(tensor([0, 1, 2]), tensor([2500, 1054, 1054]))

我尝试使用 TORCH。没有成功。如何实现?

I have a Pytorch tensor mask of dimensions,

torch.Size([8, 24, 24])

with unique values,

> torch.unique(mask, return_counts=True)
(tensor([0, 1, 2]), tensor([2093, 1054, 1461]))

I wish to randomly replace the number of 2s to 0s, such that the unique values and counts in the tensor become,

> torch.unique(mask, return_counts=True)
(tensor([0, 1, 2]), tensor([2500, 1054, 1054]))

I have tried using torch.where to no success. How can this be achieved?

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

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

发布评论

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

评论(1

紫瑟鸿黎 2025-01-28 13:55:00

可能的解决方案之一是通过查看 numpy.random.Choice

from numpy.random import choice

idx = torch.where(mask.view(-1) == 2)[0]  # get all indicies of 2 in flat tensor

num_to_change = 2500 - 2093 # as follows from example above

idx_to_change = choice(idx, size=num_to_change, replace=False)

mask.view(-1)[idx_to_change] = 0

One of the possible solutions is through flattening via view and numpy.random.choice:

from numpy.random import choice

idx = torch.where(mask.view(-1) == 2)[0]  # get all indicies of 2 in flat tensor

num_to_change = 2500 - 2093 # as follows from example above

idx_to_change = choice(idx, size=num_to_change, replace=False)

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