【神经网络笔记】——TensorFlow2.x自定义回调函数Callbacks

【神经网络笔记】——TensorFlow2.x自定义回调函数Callbacks

背景

在未知训练迭代次数的情况下,动态确定每个训练需要的迭代次数,需要设置自定义回调函数,配置acc或mse损失到达一定程度后停止训练

实例

import tensorflow as tf


class earlyStop(tf.keras.callbacks.Callback):
    def __init__(self,mode,acc_threshold=0.95,loss_threshold=0.025):
        super().__init__()
        self.mode = mode
        self.acc_threshold = acc_threshold
        self.loss_threshold = loss_threshold
    def on_epoch_end(self, epoch, logs=None):
        if self.mode=='a':#二分类
            if float(logs['acc'][-1])>self.acc_threshold:
                self.model.stop_training = True
                print("训练Early Stopping 迭代次数共计",epoch)
        elif self.mode=='b':#值回归
            if float(logs['loss'][-1])<self.loss_threshold:
                self.model.stop_training = True
                print("训练Early Stopping 迭代次数共计",epoch)

关键点


 1. 终止训练 
self.model.stop_training = True
 2. 回调函数调用
        history = model.fit(features,
                            to_categorical(labels,2),
                            epochs=epochs,  # 迭代次数
                            batch_size=batch_size,
                            verbose=2,  # 该方法训练不动 异常占比过小
                            # validation_split=0.1  # 没必要,数据集过度不平衡,参考价值不大
                            callbacks=[earlyStop(mode,acc_threshold,loss_threshold)]
                            )

总结

对于迭代次数不定的场景、需要按照条件停止训练的场景,都可以自己编写回调函数,不用官方提供的earlystopping!自力更生,慢却也最快。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大数据李菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值