【问题标题】:Compute logarithm of nonzero values in a tensor with keras用 keras 计算张量中非零值的对数
【发布时间】:2020-02-23 03:12:59
【问题描述】:

我正在尝试实现自定义损失函数,它需要对模型的输出张量中的值取对数。张量也可能包含零,所以我只想取非零值并计算对数。

输出张量的形状为 (20,224,224)。我可以使用以下函数获取沿轴 0 的非零元素的数量。

#To get the number of nonzero elements along the axis 0                
count = K.tf.count_nonzero(y,axis=0) 

但我不明白如何计算非零对数。我可以想出如下 numpy 解决方案,但不确定它是否与 keras 等效。

loss = np.log2(y, out=np.zeros_like(y), where=(y!=0)) 

有人可以帮我计算张量沿轴 0 的非零的对数吗?

【问题讨论】:

    标签: python python-3.x tensorflow keras deep-learning


    【解决方案1】:

    一种可能的方法可能会利用:

    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)
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      相关资源
      最近更新 更多