如何计算自定义keras损失函数中属于一个标签class的元素?

How to count the elements belonging to one label class in a custom keras loss function?

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

我已经实现了一个 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]
[...]

试试 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]