Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按一列中的特定值对行进行分组,并计算PyTorch中的平均值_Python_Pytorch - Fatal编程技术网

Python 按一列中的特定值对行进行分组,并计算PyTorch中的平均值

Python 按一列中的特定值对行进行分组,并计算PyTorch中的平均值,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.]. # c

样本张量:

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方法来实现这一点?

您可以使用根据类索引添加,然后除以每个标签的编号,使用以下公式计算:

#输入
x=torch.arange(30.)视图(5,6)#样本张量
c=c=torch.tensor([1,3,2,0,1],dtype=torch.long)#类指数
#为输出分配空间
结果=torch.zero((c.max()+1,x.shape[1]),dtype=x.dtype)
#使用index_add_u根据类对行进行汇总
结果.索引添加(0,c,x)
#使用“唯一”来计算每个类的数量
_,counts=torch.unique(c,return\u counts=True)
#将总和除以计数得到平均值
结果/=计数[:,无]
结果与预期一致:

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

如果输入是3D张量,我可以在没有循环的情况下执行这些操作吗?