參考資料:http://www.cnblogs.com/bnuvincent/p/7484342.html
keras2中將F1scre函數(shù)移除了炫彩,但是此函數(shù)在訓(xùn)練集平衡時(shí)比較好用佃乘,所幸我們可以通過Callback函數(shù)自定義評(píng)價(jià)函數(shù),下面是一個(gè)每回合打印F1score、準(zhǔn)確率(precision)骂远、召回率(recall)的示例(python3):
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(va_targ, val)
self.val_f1s.append(_val_f1)
self.val_recalls.append(_val_recall)
self.val_precisions.append(_val_precision)
print('-val_f1: %.4f --val_precision: %.4f --val_recall: %.4f'%(_val_f1, _val_precision, _val_recall))
return
metrics = Metrics()
需要查看訓(xùn)練過程中的評(píng)價(jià)函數(shù)值時(shí),可以直接輸出
print(metrics.val_f1s)
定義好模型后腰根,使用新的評(píng)價(jià)函數(shù)來(lái)訓(xùn)練模型:
model.fit(training_data, training_target,
validation_data=(validation_data, validation_target),
np_epoch=10, batch_size=64, callbacks =[metrics])
訓(xùn)練時(shí)的輸出: