0

I need to calculate Aitchison distance as a loss function between input and output datasets.

While calculating this mstric I need to calculate geometric mean on each row (where [batches x features] - size of a dataset during loss ).

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

So how it could be done on tensorflow? I didn't find any specified metrics or reduced functions

Anton
  • 73
  • 8
  • Is it an option [https://www.tensorflow.org/addons/api_docs/python/tfa/metrics/GeometricMean](https://www.tensorflow.org/addons/api_docs/python/tfa/metrics/GeometricMean)? – czeni Aug 02 '21 at 19:47
  • I didn't find any examples of usage, when I tried by myself tf.metrics.GeometricMean, python didn't find it "tensorflow.keras.metrics has no attribute 'GeometricMean'" – Anton Aug 02 '21 at 19:59
  • It is not part of the core tensorflow package, but an so called addon. you should first install it. See: [here](https://github.com/tensorflow/addons). – czeni Aug 03 '21 at 09:32
  • yes, I done it, but it looks like I can't use it in way I need. For example when I call geomean.update_state(yTrue) I got error. So I don't know how use it as part of loss funciton – Anton Aug 03 '21 at 09:35
  • Alright, then it seems the metric cannot be used as a loss function due to different API. In that case geometric mean have to be calculated directly with tensorflow functions. – czeni Aug 03 '21 at 09:45

1 Answers1

1

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

You can define dim according to your needs or integrate it into your code.

czeni
  • 427
  • 2
  • 11