计算张量流损失时的几何平均值 [英] geometric mean while calculationg tensorflow loss
问题描述
我需要计算 Aitchison 距离作为输入和输出数据集之间的损失函数.
I need to calculate Aitchison distance as a loss function between input and output datasets.
在计算这个 mstric 时,我需要计算每一行的几何平均值(其中 [batches x features] - 损失期间数据集的大小).
While calculating this mstric I need to calculate geometric mean on each row (where [batches x features] - size of a dataset during loss ).
在简单的情况下,我们可以想象只有 1 个批次,所以我只需要计算一个用于输入的几何平均值和一个用于输出数据集的几何平均值
In simple case we could imagine that there is only 1 batch so I need just to calculate one geomean for input and one for output dataset
那么如何在 tensorflow 上完成呢?我没有找到任何指定的指标或简化的功能
So how it could be done on tensorflow? I didn't find any specified metrics or reduced functions
推荐答案
您可以使用 tensorflow轻松计算张量的几何平均值作为损失函数(或在您的情况下作为损失函数的一部分)code> 使用数值稳定的公式在此处突出显示.提供的代码片段与 此处 遵循上述公式(和 scipy 实现).
You can easily calculate the geometric mean of a tensor as a loss function (or in your case as part of the loss function) with tensorflow
using a numerically stable formula highlighted here. The provided code fragment highly resembles to the pytorch
solution posted here that follows the abovementioned formula (and scipy implementation).
from tensorflow.python.keras import backend as K
def gmean_loss((y_true, y_pred, dim=1):
error = y_pred - y_true
logx = K.log(inputs)
return K.exp(K.mean(logx, dim=dim))
您可以根据需要定义dim
或将其集成到您的代码中.
You can define dim
according to your needs or integrate it into your code.
这篇关于计算张量流损失时的几何平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!