一种可能的方法可能会利用:
tf.where(
condition,
x=None,
y=None,
name=None
)
列出的相关函数:https://www.tensorflow.org/api_docs/python/tf
类似于您正在探索的 numpy 版本。
例如,您可能会考虑使用上述 tf.where() 函数来测试零条目,然后根据结果从原始张量 (x) 或类似形状的“一”张量中进行选择。然后,您可以计算结果张量的 log 并对结果进行最终求和等。
下面是一个使用 Colab 和 Eager 执行的示例,更明确地展示了这个想法。
%tensorflow_version 2.x
# Above only works in Google Colab.
# Also, note eager execution is default True for Tensorflow 2.0
import tensorflow as tf
y_true = tf.Variable([[2.0],[0.0],[0.0],[3.0],[4.0]])
y_pred = tf.Variable([[2.0],[-1.0],[1.0],[3.0],[4.0]])
def my_loss_function(y_true, y_pred):
print('y_true:')
print(y_true)
print('y_pred:')
print(y_pred)
y_zeros = tf.zeros_like(y_pred)
print('y_zeros:')
print(y_zeros)
y_mask = tf.math.greater(y_pred, y_zeros)
print('y_mask:')
print(y_mask)
res = tf.boolean_mask(y_pred, y_mask)
print('res:')
print(res)
logres = tf.math.log(res)
print('logres:')
print(logres)
finres = tf.math.reduce_sum(logres)
print('finres:')
print(finres)
return finres
myres = my_loss_function(y_true, y_pred)
print(myres)
我希望这会有所帮助。