gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:51:31 27 4
gpt4 key购买 nike

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

最佳答案

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

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>)

这种实现可以在例如 SciPy ( see here ) 中找到,这是一个相当稳定的库。


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

关于pytorch - 如何以可微分的方式计算几何平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59722983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com