推荐一下在一个张量中一次性替换几个值的方法?

问题描述 投票:0回答:1

有没有一种批量的方法,可以不用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这里有可能有一对(6,66)在old_values中不存在。old_new_values 包括唯一的行。

python performance pytorch vectorization tensor
1个回答
0
投票

如果你的输入张量中没有任何重复的元素,这里有一个直接的方法,使用 遮蔽 和价值分配,使用 基本索引. 我假设输入张量的数据类型是 int. 但是,你可以简单地将这段代码直接改编成其他的代码。dtypes). 下面是一个可复制的说明,并在行文注释中穿插解释。

# 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)

关于效率的一个小说明: 在整个过程中,我们从未对数据进行任何复制(即我们只在新的数据上进行操作)。观点 根据我们的需要,通过按摩形状)。) 因此,运行时间会非常快。

© www.soinside.com 2019 - 2024. All rights reserved.