【发布时间】: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