gpt4 book ai didi

python - 什么是 tf.losses.absolute_difference 的替代品

转载 作者:太空宇宙 更新时间:2023-11-04 04:12:24 34 4
gpt4 key购买 nike

我的问题是关于 TF2.0 的。没有 tf.losses.absolute_difference() 函数,也没有 tf.losses.Reduction.MEAN 属性。

我应该改用什么?TF2 中是否有已删除的 TF 函数列表,也许还有它们的替代品。

这是 TF1.x 代码,不能与 TF2 一起运行:

result = tf.losses.absolute_difference(a,b,reduction=tf.losses.Reduction.MEAN)

最佳答案

您仍然可以通过 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

或者您可以自己实现:

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

关于python - 什么是 tf.losses.absolute_difference 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099314/

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