我有一个张量和掩模。而且,我还有第二个面膜。
现在我想要张量[mask][second_mask]的变化值,但它不起作用。
我认为这是因为tensor[mask]返回一个新的张量而不是原始张量的视图,并且将值应用于tensor[mask][second_mask]不会改变原始张量的值。我的演示如下:
import torch
x = torch.linspace(1,9,9).reshape((3,3))
mask = x>5
second_mask = 0
x[mask][second_mask] = 100
print(x)
# One way to solve it is use a temp tensor be like:
t = x[mask]
t[second_mask] = 100
x[mask] = t
# but it is sooooo long, hoping for any convenient method
您可以使用索引而不是掩码:
import torch
x = torch.linspace(1,9,9).reshape((3,3))
mask_idx = torch.where(x > 5) # tuple of 1D tensors for x,y coordinates
second_mask = 0 # this is index in my understanding instead of mask, but I follow the given naming convention
# make final_mask_idx using x, y coordinates and second_mask
final_mask_idx = (mask_idx[0][second_mask], mask_idx[1][second_mask])
x[final_mask_idx] = 100