keras 自定义F1-score 保存最优模型

主要参考了

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]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值