如何以可微分的方式计算几何平均值?

Cra*_*Man 2 pytorch

如何使用 Pytorch 沿维度计算几何平均值?有些数字可能是负数。函数必须是可微的。

Ber*_*iel 6

几何平均值的已知(合理)数值稳定版本是:

import torch

def gmean(input_x, dim):
    log_x = torch.log(input_x)
    return torch.exp(torch.mean(log_x, dim=dim))

x = torch.Tensor([2.0] * 1000).requires_grad_(True)
print(gmean(x, dim=0))
# tensor(2.0000, grad_fn=<ExpBackward>)
Run Code Online (Sandbox Code Playgroud)

例如,可以在 SciPy(参见此处)中找到这种实现,它是一个非常稳定的库。


上面的实现不处理零和负数。有些人会争辩说,负数的几何平均数没有明确定义,至少在并非所有负数都为负数时。