【发布时间】:2022-01-22 00:51:12
【问题描述】:
在 PyTorch 中给定一个张量,如何构建边际概率向量
我有一个形状为 [Dim1: , Dim2: ] 的张量“A”,Dim1 中的每个元素都是从未知分布中提取的,我需要检查 Dim2 向量是否之前出现在其他 128 个样本。如果有,则该元素的边际概率增加 1 并记录在另一个形状为 [DimB: ] 的张量“B”中。迭代完成后,我将 B 中的所有元素除以 128(可能性的数量)以实现加权增量,因此目标是随着 Dim1 大小的增加接近真实分布。
如何在 PyTorch 中直接实现?我尝试使用有序词典,但速度太慢。我假设存在一种方法可以直接在 PyTorch 中完成
如果我们有一个形状为 [Dim1: , Dim2: ] 的张量 T1,我使用有序字典的粗略方法:
from collections import OrderedDict
od = OrderedDict()
T1 = torch.Tensor([[2.4, 5.5,1],
[3.44,5.43,1],
[2.4, 5.5,1],
[3.44,8.43,1],
[3.44,5.43,9],
[3.44,5.43,1], ])
print ('T1 shape',T1.shape) # -> T1 shape torch.Size([6, 3])
for i in range(T1.shape[0]):
key = ''.join([ str(int(j)) for j in T1[i].tolist()]) # creates a unique identifier (is there a better way to do this?)
if key in od:
od[key] +=1
key_place_holder = key + str(od[key]) # unique identifier if we found duplicate to keep a 0 in the final tensor
od[key_place_holder] = 0
else:
od[key] = 1
print ('len od',len(od)) # -> len od 6
list_values = [j/len(od) for i,j in od.items()]
T1_marginal_probabilities = torch.Tensor(list_values)
print ('Marginal Probs',T1_marginal_probabilities) # -> Marginal Probs tensor([0.3333, 0.3333, 0.0000, 0.1667, 0.1667, 0.0000])
最终输出如预期,因为[2.4, 5.5,1] 和[3.44,5.43,1] 的概率都是2/6,因为我们在位置重复了[2.4, 5.5,1] 2 次0 和 2。而 [3.44,5.43,1] 在位置 1 和 5 重复。
【问题讨论】: