2017-08-16 54 views
4

我希望在keras中實現一個自定義指標,用於計算召回,並假設最有可能的前k%y_pred_probs爲真。Keras基於預測值的自定義召回指標

numpy我會這樣做。對y_preds_probs進行排序。然後取值爲kth指數。注意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後端基於ky_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 

回答

2

感謝您引用我以前的答案。

在這種情況下,如果你正在使用tensorflow後臺,我會建議你使用這個tensorflow function

tf.nn.in_top_k(
    predictions, 
    targets, 
    k, 
    name=None 
) 

它輸出的bool的張量,1如果答案屬於如果頂部K和0沒有。

如果您需要更多信息,我已鏈接tensorflow文檔。我希望它有幫助。 :-)