[英]Conditionally apply tensor operations in PyTorch
I know PyTorch doesn't have a map
-like function to apply a function to each element of a tensor.我知道 PyTorch 没有像map
的 map 来应用一个 ZC1C425268E68385D1ABZ507 的每个元素的 ZC1C425268E68385D1ABZ507 So, could I do something like the following without a map
-like function in PyTorch?那么,我可以在没有map
中的 map 的情况下执行以下操作吗?
if tensor_a * tensor_b.matmul(tensor_c) < 1:
return -tensor_a*tensor_b
else:
return 0
This would work if the tensors were 1D.如果张量是一维的,这将起作用。 However, I need this to work when tensor_b
is 2D ( tensor_a
needs to be unsqueeze
d in the return
statement).但是,当tensor_b
为 2D 时,我需要它来工作( tensor_a
需要在return
语句中取消unsqueeze
d )。 This means a 2D tensor should be returned where some of the rows will be 0
vectors.这意味着应该返回一个二维张量,其中一些行将是0
向量。
Happy to use the latest features of the most recent Python version.很高兴使用最新 Python 版本的最新功能。
If I understand correctly, you are looking to return a tensor either way (hence the mapping) but by checking the condition element-wise.如果我理解正确,您希望以任何一种方式(因此映射)返回张量,但通过逐个检查条件来返回。 Assuming the shapes of tensor_a
, tensor_b
, and tensor_c
are all two dimensional, as in "simple matrices", here is a possible solution.假设tensor_a
、 tensor_b
和tensor_c
的形状都是二维的,就像在“简单矩阵”中一样,这是一个可能的解决方案。
What you're looking for is probably torch.where
, it's fairly close to a mapping where based on a condition, it will return one value or another element-wise .您正在寻找的可能是torch.where
,它非常接近基于条件的映射,它将返回一个值或另一个element-wise 。
It works like torch.where(condition, value_if, value_else)
where all three tensors have the same shape ( value_if
and value_else
can actually be floats which will be cast to tensors, filled with the same value).它像torch.where(condition, value_if, value_else)
一样工作,其中所有三个张量具有相同的形状( value_if
和value_else
实际上可以是浮点数,它们将被转换为张量,填充相同的值)。 Also, condition
is a bool tensor which defines which value to assign to the outputted tensor: it's a boolean mask.此外, condition
是一个布尔张量,它定义了分配给输出张量的值:它是一个 boolean 掩码。
For the purpose of this example, I have used random tensors:出于本示例的目的,我使用了随机张量:
>>> a = torch.rand(2, 2, dtype=float)*100
>>> b = torch.rand(2, 2, dtype=float)*0.01
>>> c = torch.rand(2, 2, dtype=float)*10
>>> torch.where(a*(b@c) < 1, -a*b, 0.)
tensor([[ 0.0000, 0.0000],
[ 0.0000, -0.0183]], dtype=torch.float64)
More generally though, this will work if tensor_a
and tensor_b
have a shape of (m, n)
, and tensor_c
has a shape of (n, m)
because of the operation constraints.更一般地说,如果tensor_a
和tensor_b
的形状为(m, n)
,并且tensor_c
的形状为(n, m)
由于操作限制,这将起作用。 In your experiment I'm guessing you only had columns.在你的实验中,我猜你只有列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.