1. 程式人生 > 程式設計 >在keras裡面實現計算f1-score的程式碼

在keras裡面實現計算f1-score的程式碼

我就廢話不多說了,大家還是直接看程式碼吧!

### 以下連結裡面的code
import numpy as np
from keras.callbacks import Callback
from sklearn.metrics import confusion_matrix,f1_score,precision_score,recall_score
class Metrics(Callback):
def on_train_begin(self,logs={}):
 self.val_f1s = []
 self.val_recalls = []
 self.val_precisions = []

def on_epoch_end(self,epoch,logs={}):
 val_predict = (np.asarray(self.model.predict(self.model.validation_data[0]))).round()
 val_targ = self.model.validation_data[1]
 _val_f1 = f1_score(val_targ,val_predict)
 _val_recall = recall_score(val_targ,val_predict)
 _val_precision = precision_score(val_targ,val_predict)
 self.val_f1s.append(_val_f1)
 self.val_recalls.append(_val_recall)
 self.val_precisions.append(_val_precision)
 print “ — val_f1: %f — val_precision: %f — val_recall %f” %(_val_f1,_val_precision,_val_recall)
 return

metrics = Metrics()
model.fit(
 train_instances.x,train_instances.y,batch_size,epochs,verbose=2,callbacks=[metrics],validation_data=(valid_instances.x,valid_instances.y),)

補充知識:Keras可使用的評價函式

1:binary_accuracy(對二分類問題,計算在所有預測值上的平均正確率)

binary_accuracy(y_true,y_pred)

2:categorical_accuracy(對多分類問題,計算在所有預測值上的平均正確率)

categorical_accuracy(y_true,y_pred)

3:sparse_categorical_accuracy(與categorical_accuracy相同,在對稀疏的目標值預測時有用 )

sparse_categorical_accuracy(y_true,y_pred)

4:top_k_categorical_accuracy(計算top-k正確率,當預測值的前k個值中存在目標類別即認為預測正確 )

top_k_categorical_accuracy(y_true,y_pred,k=5)

5:sparse_top_k_categorical_accuracy(與top_k_categorical_accracy作用相同,但適用於稀疏情況)

sparse_top_k_categorical_accuracy(y_true,k=5)

以上這篇在keras裡面實現計算f1-score的程式碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。