主要参考了
Tensorflow与keras学习 (8)——实现f1_score(多分类、二分类)_AI小白龙的博客-CSDN博客
在参考第一个的时候出现了
self.validation is NoneType
解决:
class Metrics(Callback):
def __init__(self, train_x, train_y, val_x, val_y, file_path, batch_size = 1024):
super().__init__()
self.train_x = train_x
self.train_y = train_y
self.val_x = val_x
self.val_y = val_y
self.batch_size = batch_size
self.file_path = file_path
self.best_val_f1=0
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.validation_data[0]))).round()
# print('*************self.validation_data',self.validation_data)
train_predict = np.argmax(np.asarray(self.model.predict(self.train_x )), axis=1)
train_targ = np.argmax(self.train_y, axis=1)
_train_f1 = f1_score(train_targ, train_predict, average='weighted')
val_predict = np.argmax(np.asarray(self.model.predict(self.val_x )), axis=1)
val_targ = np.argmax(self.val_y, axis=1)
_val_f1 = f1_score(val_targ, val_predict, average='weighted')
self.val_f1s.append(_val_f1)
print(' _train_f1: ',_train_f1, ' val_f1:' ,_val_f1)
if _val_f1 > self.best_val_f1:
self.best_val_f1 = _val_f1
self.model.save(self.file_path, overwrite=True)
print("best f1: {} model saved ".format(self.best_val_f1))
else:
print("val f1: {}, but not the best f1".format(_val_f1))
return
metric = Metrics(train_x, train_y, valid_x, valid_y)
callbacks = [metric]