python - 按一列中的特定值对行进行分组并在 PyTorch 中计算平均值

标签 python pytorch

样本张量:

tensor([[ 0.,  1.,  2.,  3.,  4.,  5.],  # class1
        [ 6.,  7.,  8.,  9., 10., 11.],  # class3
        [12., 13., 14., 15., 16., 17.],  # class2
        [18., 19., 20., 21., 22., 23.],  # class0
        [24., 25., 26., 27., 28., 29.].  # class1
])

预期结果:

tensor([[18., 19., 20., 21., 22., 23.], # class0
        [12., 13., 14., 15., 16., 17.], # class1
        [12., 13., 14., 15., 16., 17.], # class2
        [ 6.,  7.,  8.,  9., 10., 11.]. # class3
]) 

有没有一个纯 PyTorch 方法来实现这个?

最佳答案

您可以使用 index_add 根据类索引添加然后除以每个标签的数量,使用 unique 计算得出:

# inputs
x = torch.arange(30.).view(5,6)  # sample tensor
c = c = torch.tensor([1, 3, 2, 0, 1], dtype=torch.long)  # class indices

# allocate space for output
result = torch.zeros((c.max() + 1, x.shape[1]), dtype=x.dtype)
# use index_add_ to sum up rows according to class
result.index_add_(0, c, x)
# use "unique" to count how many of each class
_, counts = torch.unique(c, return_counts=True)
# divide the sum by the counts to get the average
result /= counts[:, None]

结果符合预期:

Out[*]:
tensor([[18., 19., 20., 21., 22., 23.],
        [12., 13., 14., 15., 16., 17.],
        [12., 13., 14., 15., 16., 17.],
        [ 6.,  7.,  8.,  9., 10., 11.]])

关于python - 按一列中的特定值对行进行分组并在 PyTorch 中计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62424100/

相关文章:

python - 将范围指定为仅选择填充单元格/以空单元格结尾 Python

python - 用于解压缩带有大括号抑制的列表的 f-string 语法

python - Pytorch:丢失层和打包序列

pytorch - torch.masked_scatter 结果不符合预期

python - 尝试将带有边缘的 txt.file 转换为边缘列表

python - 如何在 virtualenv 中安装 python3-gi?

python - 如何优化具有带条件的嵌套列表的Python代码?

c++ - torch C++ : Getting the value of a int tensor by using *. 数据<int>()

python - pytorch 中的 Keras 学习率衰减

pytorch - 如何在多次运行中重现 RNN 结果?