【问题标题】:How to count the elements belonging to one label class in a custom keras loss function?如何在自定义 keras 损失函数中计算属于一个标签类的元素?
【发布时间】:2019-10-14 15:55:18
【问题描述】:

我正在寻找一种方法来计算自定义损失函数中 y_true 数组中每个类的出现次数,并将数组中的每个元素替换为其各自的出现次数。

我已经实现了一个 numpy 解决方案,但我似乎无法将它翻译成 keras(带有 tf 后端)。

示例输入:

y_true = np.array([0, 1, 1, 1, 0, 3])

进口:

import numpy as np
from keras import backend as k

Numpy 实现:

def custom_loss(y_true, y_pred):
    bins = np.bincount(y_true)
    y_true_counts = bins[y_true]

    >>> y_true_counts: [2 3 3 3 2 1]

Keras 实现:

def custom_loss(y_true, y_pred)
    bins = k.tf.bincount(y_true)
    y_true_counts = bins[y_true]

虽然 numpy 解决方案工作正常,但当我想评估 keras 实现时,我收到以下错误:

a = custom_loss(y_true, y_pred)
>>> InvalidArgumentError: Shape must be rank 1 but is rank 2 for 'strided_slice_4' (op: 'StridedSlice') with input shapes: [?], [1,6], [1,6], [1].
[...]
----> 3     y_true_counts = bins[y_true]
[...]

【问题讨论】:

    标签: python numpy tensorflow keras loss-function


    【解决方案1】:

    试试tf.bincounttf.gather

    import tensorflow as tf
    
    y_true = tf.constant([0, 1, 1, 1, 0, 3],dtype=tf.int32)
    bins = tf.bincount(y_true)
    y_true_counts = tf.gather(bins,y_true)
    
    with tf.Session()as sess:
        print(sess.run(bins))
        print(sess.run(y_true_counts))
    
    [2 3 0 1]
    [2 3 3 3 2 1]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-05
      • 2020-04-14
      • 2020-12-19
      • 2017-12-18
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      相关资源
      最近更新 更多