[英]How can I get one array to return only the masked values define by another array with Numpy / PyTorch?
I have a mask
, which has a shape of: [64, 2895]
and an array pred
which has a shape of [64, 2895, 161]
.我有一个
mask
,其形状为: [64, 2895]
和一个数组pred
,其形状为[64, 2895, 161]
。
mask
is binary with only 0
s and 1
s. mask
是二进制的,只有0
s 和1
s。 What I want to do is reduce pred
so that it maintains 64
batches, and along the 2895
, wherever there is a 1
in the mask
for each batch, return the related pred
.我想要做的是减少
pred
以便它保持64
批次,并且沿着2895
,只要每个批次的mask
有1
,就返回相关的pred
。
So as a simplified example, if:所以作为一个简化的例子,如果:
mask = [[1, 0, 0],
[1, 1, 0],
[0, 0, 1]]
pred = [[[0.12, 0.23, 0.45, 0.56, 0.57],
[0.91, 0.98, 0.97, 0.96, 0.95],
[0.24, 0.46, 0.68, 0.80, 0.15]],
[[1.12, 1.23, 1.45, 1.56, 1.57],
[1.91, 1.98, 1.97, 1.96, 1.95],
[1.24, 1.46, 1.68, 1.80, 1.15]],
[[2.12, 2.23, 2.45, 2.56, 2.57],
[2.91, 2.98, 2.97, 2.96, 2.95],
[2.24, 2.46, 2.68, 2.80, 2.15]]]
What I want is:我想要的是:
[[[0.12, 0.23, 0.45, 0.56, 0.57]],
[[1.12, 1.23, 1.45, 1.56, 1.57],
[1.91, 1.98, 1.97, 1.96, 1.95]],
[[2.24, 2.46, 2.68, 2.80, 2.15]]]
I realize that there are different dimensions, I hope that that's possible.我意识到有不同的维度,我希望这是可能的。 If not, then fill in the missing dimensions with
0
.如果不是,则用
0
填充缺失的维度。 Either numpy
or pytorch
would be helpful. numpy
或pytorch
都会有所帮助。 Thank you.谢谢你。
If you want a vectorized computation then different dimension seems not possible, but this would give you the one with masked entry filled with 0:如果你想要一个矢量化计算,那么不同的维度似乎是不可能的,但这会给你一个用 0 填充的掩码条目:
# pred: torch.size([64, 2895, 161])
# mask: torch.size([64, 2895])
result = pred * mask[:, :, None]
# extend mask with another dimension so now it can do entry-wise multiplication
and result
is exactly what you want result
正是你想要的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.