简体   繁体   English

在 PyTorch 中有条件地应用张量操作

[英]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_atensor_btensor_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_ifvalue_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_atensor_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM