4
我希望在keras中實現一個自定義指標,用於計算召回,並假設最有可能的前k%y_pred_probs
爲真。Keras基於預測值的自定義召回指標
在numpy
我會這樣做。對y_preds_probs進行排序。然後取值爲k
th指數。注意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 custom decision threshold for precision and recall是相當接近,但假設這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