如何将pytorch中的直方图函数应用到特定的轴上?

How to apply the histogram function in pytorch to a specific axis?

我想对训练批次中的不同样本使用 torch.histc 函数。 这是一个例子:

>>> tt2 = torch.from_numpy(np.array([[-0.2, 1, 0.21], [-0.1, 0.32, 0.2]]))
>>> tt3 = torch.from_numpy(np.array([[-0.8, 0.6, 0.1], [-0.6, 0.5, 0.4]]))
>>> t = torch.cat((tt2, tt3), 1)
>>> t
tensor([[-0.2000,  1.0000,  0.2100, -0.8000,  0.6000,  0.1000],
        [-0.1000,  0.3200,  0.2000, -0.6000,  0.5000,  0.4000]],
       dtype=torch.float64)
>>> torch.histc(t, bins=1, min=0, max=5)
tensor([8.], dtype=torch.float64)

但是,我不想对 t 中的所有值应用直方图函数,我更希望这样:

>>> torch.histc(torch.tensor([[-0.2000,  1.0000,  0.2100, -0.8000,  0.6000,  0.1000]]), bins=1, min=0, max=5)
tensor([4.])
>>> torch.histc(torch.tensor([[-0.1000,  0.3200,  0.2000, -0.6000,  0.5000,  0.4000]]), bins=1, min=0, max=5)
tensor([4.])
>>>

最后,我想将所有直方图聚合在同一个张量中:tensor([[4.], [4.]])。 提前致谢

这个函数解决了问题,但我不确定这是不是最pythonic的方法:

import numpy as np

def funct(semembs_as, semembs_bs):
    t = torch.cat((semembs_as, semembs_bs), 1)
    # make prediction a value between 0.0 and 5.0
    l = [torch.histc(ti, bins=1, min=0, max=5) for ti in t]
    y = [list(e) for e in l]
    return torch.from_numpy(np.array(y))

t1 = torch.from_numpy(np.array([[-0.2, 1, 0.21], [-0.1, 0.32, 0.2]]))
t2 = torch.from_numpy(np.array([[0.7, 0.0, -0.6], [-0.6, 0.5, 0.4]]))

x = funct(t1, t2)
x

tensor([[4.], [4.]], dtype=torch.float64)

如果您有更好的解决方案,请不要犹豫,发表评论。

你可以试试这个:

import torch
torch.manual_seed(1)

bins = 1
    
t = torch.rand((2, 6))
    
tuple_rows = torch.tensor_split(t, t.shape[0], dim=0)
    
final_tensor = torch.empty((t.shape[0],bins))
    
for i,row in enumerate(tuple_rows):
  final_tensor[i] = torch.histc(row, bins=1, min=0, max=5)

final_tensor : tensor([[6.], [6.]])