Reputation: 216
My question is about in TF2.0
. There is no tf.losses.absolute_difference()
function and also there is no tf.losses.Reduction.MEAN
attribute.
What should I use instead?
Is there a list of deleted TF
functions in TF2
and perhaps their replacement.
This is TF1.x
code which does not run with TF2
:
result = tf.losses.absolute_difference(a,b,reduction=tf.losses.Reduction.MEAN)
Upvotes: 2
Views: 1383
Reputation: 8595
You still can access this function via tf.compat.v1
:
import tensorflow as tf
labels = tf.constant([[0, 1], [1, 0], [0, 1]])
predictions = tf.constant([[0, 1], [0, 1], [1, 0]])
res = tf.compat.v1.losses.absolute_difference(labels,
predictions,
reduction=tf.compat.v1.losses.Reduction.MEAN)
print(res.numpy()) # 0.6666667
Or you could implement it yourself:
import tensorflow as tf
from tensorflow.python.keras.utils import losses_utils
def absolute_difference(labels, predictions, weights=1.0, reduction='mean'):
if reduction == 'mean':
reduction_fn = tf.reduce_mean
elif reduction == 'sum':
reduction_fn = tf.reduce_sum
else:
# You could add more reductions
pass
labels = tf.cast(labels, tf.float32)
predictions = tf.cast(predictions, tf.float32)
losses = tf.abs(tf.subtract(predictions, labels))
weights = tf.cast(tf.convert_to_tensor(weights), tf.float32)
res = losses_utils.compute_weighted_loss(losses,
weights,
reduction=tf.keras.losses.Reduction.NONE)
return reduction_fn(res, axis=None)
res = absolute_difference(labels, predictions)
print(res.numpy()) # 0.6666667
Upvotes: 3