我想在 keras 中实现一个自定义指标,假设前 k% 最有可能y_pred_probs
为真,计算召回率。
在numpy
中,我会这样做如下。对y_preds_probs进行排序。然后取第k
个索引处的值。注意k=0.5
将给出中值。
kth_pos = int(k * len(y_pred_probs))
threshold = np.sort(y_pred_probs)[::-1][kth_pos]
y_pred = np.asarray([1 if i >= threshold else 0 for i in y_pred_probs])
答案来自:Keras 自定义精度和召回率的决策阈值非常接近,但假设决定哪些y_pred
假定为真的阈值是已知的。如果可能的话,我想结合这些方法,并根据 Keras 后端中的k
和y_pred
实现查找threshold_value。
def recall_at_k(y_true, y_pred):
"""Recall metric.
Computes the recall over the whole batch using threshold_value from k-th percentile.
"""
###
threshold_value = # calculate value of k-th percentile of y_pred here
###
# Adaptation of the "round()" used before to get the predictions. Clipping to make sure that the predicted raw values are between 0 and 1.
y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), threshold_value), K.floatx())
# Compute the number of true positives. Rounding in prevention to make sure we have an integer.
true_positives = K.round(K.sum(K.clip(y_true * y_pred, 0, 1)))
# Compute the number of positive targets.
possible_positives = K.sum(K.clip(y_true, 0, 1))
recall_ratio = true_positives / (possible_positives + K.epsilon())
return recall_ratio
感谢您引用我之前的答案。
在这种情况下,如果你使用的是张量流后端,我建议你使用这个张量流函数:
tf.nn.in_top_k(
predictions,
targets,
k,
name=None
)
它输出一个布尔张量,如果答案属于前 k 个,则为 1,如果不属于,则为 0。
如果您需要更多信息,我已经链接了张量流文档。我希望它有所帮助。:-)