python - 一次替换张量中的多个值的推荐方法?

标签 python performance pytorch vectorization tensor

是否有一种批处理方法可以在没有 for 循环的情况下一次替换 pytorch 张量中的多个特定值?

例子:

old_values = torch.Tensor([1, 2, 3, 4, 5, 5, 2, 3, 3, 2])
old_new_value = [[2,22], [3,33], [6, 66]]

old_new_value = [[2,22], [3,33], [6, 66]],意思是2应该换成22,3应该换成33和6到 66

我能否有一种有效的方法来实现以下 end_result?

end_result = torch.Tensor([1, 22, 33, 4, 5, 5, 22, 33, 33, 22])

请注意,old_values 不是唯一的。另外,old_new_value 可能有一对 old_values 中不存在的 here(6, 66)。 此外,old_new_values 包含唯一行,

最佳答案

如果您的输入张量中没有任何重复元素,这是使用掩码 和使用基本索引 赋值的一种直接方法。 (我假设输入张量的数据类型是 int。但是,您可以直接将此代码改编为其他 dtype)。下面是一个可重现的插图,解释散布在行内注释中。

# input tensors to work with
In [75]: old_values    
Out[75]: tensor([1, 2, 3, 4, 5], dtype=torch.int32)

In [77]: old_new_value      
Out[77]:
tensor([[ 2, 22],
        [ 3, 33]], dtype=torch.int32)

# generate a boolean mask using the values that need to be replaced (i.e. 2 & 3)
In [78]: boolean_mask = (old_values == old_new_value[:, :1]).sum(dim=0).bool() 

In [79]: boolean_mask 
Out[79]: tensor([False,  True,  True, False, False])

# assign the new values by basic indexing
In [80]: old_values[boolean_mask] = old_new_value[:, 1:].squeeze() 

# sanity check!
In [81]: old_values 
Out[81]: tensor([ 1, 22, 33,  4,  5], dtype=torch.int32)

关于效率的小提示:在整个过程中,我们从未制作任何数据副本(即我们仅通过根据我们的需求)。因此,运行时间将非常快。

关于python - 一次替换张量中的多个值的推荐方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62185188/

相关文章:

python - Django - 使用自定义的 login_required 装饰器保护 Apache 提供的媒体文件

python - 在solaris操作系统中运行python命令

python - 针对小任意浮点值的 arcsin 函数的最快可能方法

python - 更 Pythonic 的方式 - Pandas 数据帧操作

python - pytorch 1.3.1 中的 '_DataLoaderIter' 在哪里?

python - 如何与 tensorflow 保存的模型预测器并行进行推理?

python - 使用 if-return-return 还是 if-else-return 效率更高?

javascript - 为什么加载一些css和js文件需要很长时间?

pytorch - 如何在 Google Colab 上安装 PyTorch v1.0.0+?

python - 我应该运行一个单独的线程来将模型保存在 Pytorch 中吗