keras 自定義 metrics


keras 自定義 metrics

 
ilufei2019  2018-11-26 14:36:00 瀏覽2698
 
展開閱讀全文

自定義 Metrics

在 keras 中操作的均為 Tensor 對象,因此,需要定義操作 Tensor 的函數來操作所有輸出結果,定義好函數之后,直接將其放在 model.compile 函數 metrics 中即可生效:

def precision(y_true, y_pred): # Calculates the precision true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def recall(y_true, y_pred): # Calculates the recall true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def fbeta_score(y_true, y_pred, beta=1): # Calculates the F score, the weighted harmonic mean of precision and recall. if beta < 0: raise ValueError('The lowest choosable beta is zero (only precision).') # If there are no true positives, fix the F score at 0 like sklearn. if K.sum(K.round(K.clip(y_true, 0, 1))) == 0: return 0 p = precision(y_true, y_pred) r = recall(y_true, y_pred) bb = beta ** 2 fbeta_score = (1 + bb) * (p * r) / (bb * p + r + K.epsilon()) return fbeta_score def fmeasure(y_true, y_pred): # Calculates the f-measure, the harmonic mean of precision and recall. return fbeta_score(y_true, y_pred, beta=1) 

使用方法如下:

model.compile( 
    optimizer=Adam(), 
    loss='binary_crossentropy', metrics = ['accuracy', fmeasure, recall, precision]) 

參考

custom metrics for binary classification in Keras


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM