参考资料:http://www.cnblogs.com/bnuvincent/p/7484342.html
keras2中将F1scre函数移除了,但是此函数在训练集平衡时比较好用,所幸我们可以通过Callback函数自定义评价函数,下面是一个每回合打印F1score、准确率(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()
需要查看训练过程中的评价函数值时,可以直接输出
print(metrics.val_f1s)
定义好模型后,使用新的评价函数来训练模型:
model.fit(training_data, training_target,
validation_data=(validation_data, validation_target),
np_epoch=10, batch_size=64, callbacks =[metrics])
训练时的输出: