广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python中Hook钩子函数的作用是什么
  • 699
分享到

Python中Hook钩子函数的作用是什么

2023-06-15 21:06:44 699人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

本篇文章为大家展示了python中Hook钩子函数的作用是什么,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1. 什么是Hook经常会听到钩子函数(hook function)这个概念,最近在看目标

本篇文章为大家展示了python中Hook钩子函数的作用是什么,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

1. 什么是Hook

经常会听到钩子函数(hook function)这个概念,最近在看目标检测开源框架mmdetection,里面也出现大量Hook的编程方式,那到底什么是hook?hook的作用是什么?

  •  what is hook ?钩子hook,顾名思义,可以理解是一个挂钩,作用是有需要的时候挂一个东西上去。具体的解释是:钩子函数是把我们自己实现的hook函数在某一时刻挂接到目标挂载点上。

  •  hook函数的作用 举个例子,hook的概念在windows桌面软件开发很常见,特别是各种事件触发的机制; 比如c++的MFC程序中,要监听鼠标左键按下的时间,MFC提供了一个onLefTKEyDown的钩子函数。很显然,MFC框架并没有为我们实现onLeftKeyDown具体的操作,只是为我们提供一个钩子,当我们需要处理的时候,只要去重写这个函数,把我们需要操作挂载在这个钩子里,如果我们不挂载,MFC事件触发机制中执行的就是空的操作。

从上面可知

  •  hook函数是程序中预定义好的函数,这个函数处于原有程序流程当中(暴露一个钩子出来)

  •  我们需要再在有流程中钩子定义的函数块中实现某个具体的细节,需要把我们的实现,挂接或者注册(reGISter)到钩子里,使得hook函数对目标可用

  •  hook 是一种编程机制,和具体的语言没有直接的关系

  •  如果从设计模式上看,hook模式是模板方法的扩展

  •  钩子只有注册的时候,才会使用,所以原有程序的流程中,没有注册或挂载时,执行的是空(即没有执行任何操作)

本文用Python来解释hook的实现方式,并展示在开源项目中hook的应用案例。hook函数和我们常听到另外一个名称:回调函数(callback function)功能是类似的,可以按照同种模式来理解。

Python中Hook钩子函数的作用是什么

2. hook实现例子

据我所知,hook函数最常使用在某种流程处理当中。这个流程往往有很多步骤。hook函数常常挂载在这些步骤中,为增加额外的一些操作,提供灵活性。

下面举一个简单的例子,这个例子的目的是实现一个通用往队列中插入内容的功能。流程步骤有2个

  •  需要再插入队列前,对数据进行筛选 input_filter_fn

  •  插入队列 insert_queue 

class ContentStash(object):      """      content stash for online operation      pipeline is      1. input_filter: filter some contents, no use to user      2. insert_queue(redis or other broker): insert useful content to queue      """      def __init__(self):          self.input_filter_fn = None          self.broker = []      def register_input_filter_hook(self, input_filter_fn):          """          register input filter function, parameter is content dict          Args:              input_filter_fn: input filter function          Returns:          """          self.input_filter_fn = input_filter_fn      def insert_queue(self, content):          """          insert content to queue          Args:              content: dict         Returns:         """          self.broker.append(content)      def input_pipeline(self, content, use=False):          """          pipeline of input for content stash          Args:              use: is use, defaul False              content: dict         Returns:          """          if not use:              return          # input filter          if self.input_filter_fn:              _filter = self.input_filter_fn(content)                  # insert to queue         if not _filter:              self.insert_queue(content)   # test  ## 实现一个你所需要的钩子实现:比如如果content 包含time就过滤掉,否则插入队列  def input_filter_hook(content):      """      test input filter hook      Args:          content: dict      Returns: None or content      """      if content.get('time') is None:          return      else:          return content  # 原有程序  content = {'filename': 'test.jpg', 'b64_file': "#test", 'data': {"result": "cat", "probility": 0.9}}  content_stash = ContentStash('audit', work_dir='')  # 挂上钩子函数, 可以有各种不同钩子函数的实现,但是要主要函数输入输出必须保持原有程序中一致,比如这里是content  content_stash.register_input_filter_hook(input_filter_hook)  # 执行流程  content_stash.input_pipeline(content)

3. hook在开源框架中的应用

3.1 keras

深度学习训练流程中,hook函数体现的淋漓尽致。

一个训练过程(不包括数据准备),会轮询多次训练集,每次称为一个epoch,每个epoch又分为多个batch来训练。流程先后拆解成:

  •  开始训练

  •  训练一个epoch前

  •  训练一个batch前

  •  训练一个batch后

  •  训练一个epoch后

  •  评估验证集

  •  结束训练

这些步骤是穿插在训练一个batch数据的过程中,这些可以理解成是钩子函数,我们可能需要在这些钩子函数中实现一些定制化的东西,比如在训练一个epoch后我们要保存下训练的模型,在结束训练时用最好的模型执行下测试集的效果等等。

keras中是通过各种回调函数来实现钩子hook功能的。这里放一个callback的父类,定制时只要继承这个父类,实现你过关注的钩子就可以了。

@keras_export('keras.callbacks.Callback')  class Callback(object):    """Abstract base class used to build new callbacks.    Attributes:        params: Dict. Training parameters            (eg. verbosity, batch size, number of epochs...).        model: Instance of `keras.models.Model`.            Reference of the model being trained.    The `logs` dictionary that callback methods    take as argument will contain keys for quantities relevant to    the current batch or epoch (see method-specific docstrings).    """    def __init__(self):      self.validation_data = None  # pylint: disable=g-missing-from-attributes      self.model = None      # Whether this Callback should only run on the chief worker in a      # Multi-Worker setting.      # TODO(omalleyt): Make this attr public once solution is stable.      self._chief_worker_only = None      self._supports_tf_logs = False    def set_params(self, params):      self.params = params    def set_model(self, model):      self.model = model    @doc_controls.for_subclass_implementers    @generic_utils.default    def on_batch_begin(self, batch, logs=None):      """A backwards compatibility alias for `on_train_batch_begin`."""    @doc_controls.for_subclass_implementers    @generic_utils.default    def on_batch_end(self, batch, logs=None):      """A backwards compatibility alias for `on_train_batch_end`."""    @doc_controls.for_subclass_implementers    def on_epoch_begin(self, epoch, logs=None):      """Called at the start of an epoch.       Subclasses should override for any actions to run. This function should only      be called during TRAIN mode.     Arguments:          epoch: Integer, index of epoch.          logs: Dict. Currently no data is passed to this argument for this method            but that may change in the future.      """    @doc_controls.for_subclass_implementers    def on_epoch_end(self, epoch, logs=None):      """Called at the end of an epoch.      Subclasses should override for any actions to run. This function should only      be called during TRAIN mode.      Arguments:          epoch: Integer, index of epoch.          logs: Dict, metric results for this training epoch, and for the            validation epoch if validation is perfORMed. Validation result keys            are prefixed with `val_`.      """   @doc_controls.for_subclass_implementers    @generic_utils.default    def on_train_batch_begin(self, batch, logs=None):      """Called at the beginning of a training batch in `fit` methods.      Subclasses should override for any actions to run.      Arguments:          batch: Integer, index of batch within the current epoch.          logs: Dict, contains the return value of `model.train_step`. Typically,            the values of the `Model`'s metrics are returned.  Example:            `{'loss': 0.2, 'accuracy': 0.7}`.      """      # For backwards compatibility.      self.on_batch_begin(batch, logslogs=logs)    @doc_controls.for_subclass_implementers    @generic_utils.default    def on_train_batch_end(self, batch, logs=None):      """Called at the end of a training batch in `fit` methods.      Subclasses should override for any actions to run.      Arguments:          batch: Integer, index of batch within the current epoch.          logs: Dict. Aggregated metric results up until this batch.      """      # For backwards compatibility.      self.on_batch_end(batch, logslogs=logs)    @doc_controls.for_subclass_implementers    @generic_utils.default    def on_test_batch_begin(self, batch, logs=None):      """Called at the beginning of a batch in `evaluate` methods.      Also called at the beginning of a validation batch in the `fit`      methods, if validation data is provided.      Subclasses should override for any actions to run.      Arguments:          batch: Integer, index of batch within the current epoch.          logs: Dict, contains the return value of `model.test_step`. Typically,            the values of the `Model`'s metrics are returned.  Example:            `{'loss': 0.2, 'accuracy': 0.7}`.      """    @doc_controls.for_subclass_implementers    @generic_utils.default    def on_test_batch_end(self, batch, logs=None):      """Called at the end of a batch in `evaluate` methods.      Also called at the end of a validation batch in the `fit`      methods, if validation data is provided.      Subclasses should override for any actions to run.      Arguments:          batch: Integer, index of batch within the current epoch.          logs: Dict. Aggregated metric results up until this batch.      """    @doc_controls.for_subclass_implementers    @generic_utils.default    def on_predict_batch_begin(self, batch, logs=None):      """Called at the beginning of a batch in `predict` methods.      Subclasses should override for any actions to run.      Arguments:          batch: Integer, index of batch within the current epoch.          logs: Dict, contains the return value of `model.predict_step`,            it typically returns a dict with a key 'outputs' containing            the model's outputs.      """   @doc_controls.for_subclass_implementers    @generic_utils.default    def on_predict_batch_end(self, batch, logs=None):      """Called at the end of a batch in `predict` methods.      Subclasses should override for any actions to run.      Arguments:          batch: Integer, index of batch within the current epoch.          logs: Dict. Aggregated metric results up until this batch.      """   @doc_controls.for_subclass_implementers    def on_train_begin(self, logs=None):      """Called at the beginning of training.       Subclasses should override for any actions to run.      Arguments:          logs: Dict. Currently no data is passed to this argument for this method            but that may change in the future.      """    @doc_controls.for_subclass_implementers    def on_train_end(self, logs=None):      """Called at the end of training.       Subclasses should override for any actions to run.      Arguments:          logs: Dict. Currently the output of the last call to `on_epoch_end()`            is passed to this argument for this method but that may change in            the future.      """   @doc_controls.for_subclass_implementers    def on_test_begin(self, logs=None):      """Called at the beginning of evaluation or validation.      Subclasses should override for any actions to run.      Arguments:          logs: Dict. Currently no data is passed to this argument for this method            but that may change in the future.      """    @doc_controls.for_subclass_implementers    def on_test_end(self, logs=None):      """Called at the end of evaluation or validation.      Subclasses should override for any actions to run.      Arguments:          logs: Dict. Currently the output of the last call to            `on_test_batch_end()` is passed to this argument for this method            but that may change in the future.      """    @doc_controls.for_subclass_implementers    def on_predict_begin(self, logs=None):      """Called at the beginning of prediction.     Subclasses should override for any actions to run.      Arguments:          logs: Dict. Currently no data is passed to this argument for this method            but that may change in the future.      """   @doc_controls.for_subclass_implementers    def on_predict_end(self, logs=None):      """Called at the end of prediction.      Subclasses should override for any actions to run.      Arguments:          logs: Dict. Currently no data is passed to this argument for this method            but that may change in the future.      """    def _implements_train_batch_hooks(self):      """Determines if this Callback should be called for each train batch."""      return (not generic_utils.is_default(self.on_batch_begin) or              not generic_utils.is_default(self.on_batch_end) or              not generic_utils.is_default(self.on_train_batch_begin) or              not generic_utils.is_default(self.on_train_batch_end))

这些钩子的原始程序是在模型训练流程中的

keras源码位置: Tensorflow\python\keras\engine\training.py

部分摘录如下(## I am hook):

# Container that configures and calls `tf.keras.Callback`s.        if not isinstance(callbacks, callbacks_module.CallbackList):          callbacks = callbacks_module.CallbackList(              callbacks,              add_history=True,              add_progbar=verbose != 0,              model=self,              verboseverbose=verbose,              epochsepochs=epochs,              steps=data_handler.inferred_steps)        ## I am hook        callbacks.on_train_begin()        training_logs = None        # Handle fault-tolerance for multi-worker.        # TODO(omalleyt): Fix the ordering issues that mean this has to        # happen after `callbacks.on_train_begin`.        data_handler._initial_epoch = (  # pylint: disable=protected-access            self._maybe_load_initial_epoch_from_ckpt(initial_epoch))        for epoch, iterator in data_handler.enumerate_epochs():          self.reset_metrics()          callbacks.on_epoch_begin(epoch)          with data_handler.catch_stop_iteration():            for step in data_handler.steps():              with trace.Trace(                  'TraceContext',                  graph_type='train',                  epochepoch_num=epoch,                  stepstep_num=step,                  batch_sizebatch_size=batch_size):                ## I am hook                callbacks.on_train_batch_begin(step)                tmp_logs = train_function(iterator)                if data_handler.should_sync:                  context.async_wait()                logs = tmp_logs  # No error, now safe to assign to logs.                end_step = step + data_handler.step_increment                callbacks.on_train_batch_end(end_step, logs)          epoch_logs = copy.copy(logs)          # Run validation.          ## I am hook          callbacks.on_epoch_end(epoch, epoch_logs)

3.2 mmdetection

mmdetection是一个目标检测的开源框架,集成了许多不同的目标检测深度学习算法PyTorch版),如faster-rcnn, fpn, retianet等。里面也大量使用了hook,暴露给应用实现流程中具体部分。

def train_detector(model,                     dataset,                     cfg,                     distributed=False,                     validate=False,                     timestamp=None,                     meta=None):      logger = get_root_logger(cfg.log_level)      # prepare data loaders      # put model on gpus      # build runner      optimizer = build_optimizer(model, cfg.optimizer)      runner = EpocHBasedRunner(          model,          optimizeroptimizer=optimizer,          work_dir=cfg.work_dir,          loggerlogger=logger,          metameta=meta)      # an ugly workaround to make .log and .log.JSON filenames the same      runner.timestamp = timestamp      # fp16 setting      # register hooks      runner.register_training_hooks(cfg.lr_config, optimizer_config,                                     cfg.checkpoint_config, cfg.log_config,                                     cfg.get('momentum_config', None))      if distributed:          runner.register_hook(DistSamplerSeedHook())      # register eval hooks      if validate:          # Support batch_size > 1 in validation          eval_cfg = cfg.get('evaluation', {})          eval_hook = DistEvalHook if distributed else EvalHook          runner.register_hook(eval_hook(val_dataloader, **eval_cfg))      # user-defined hooks      if cfg.get('custom_hooks', None):          custom_hooks = cfg.custom_hooks          assert isinstance(custom_hooks, list), \              f'custom_hooks expect list type, but Got {type(custom_hooks)}'          for hook_cfg in cfg.custom_hooks:              assert isinstance(hook_cfg, dict), \                  'Each item in custom_hooks expects dict type, but got ' \                  f'{type(hook_cfg)}'              hook_cfghook_cfg = hook_cfg.copy()              priority = hook_cfg.pop('priority', 'NORMAL')              hook = build_from_cfg(hook_cfg, HOOKS)              runner.register_hook(hook, prioritypriority=priority)

上述内容就是Python中Hook钩子函数的作用是什么,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注编程网Python频道。

--结束END--

本文标题: Python中Hook钩子函数的作用是什么

本文链接: https://www.lsjlt.com/news/281726.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python中Hook钩子函数的作用是什么
    本篇文章为大家展示了Python中Hook钩子函数的作用是什么,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1. 什么是Hook经常会听到钩子函数(hook function)这个概念,最近在看目标...
    99+
    2023-06-15
  • vue钩子函数的作用是什么
    Vue钩子函数的作用是在组件生命周期的不同阶段执行特定的代码逻辑。它们使开发者能够在组件的不同生命周期阶段进行自定义操作,以满足不同...
    99+
    2023-08-08
    vue
  • 详解JavaScript中的before-after-hook钩子函数
    目录before-after-hook1.单独的钩子2.Hook collectionbefore-after-hook 最近看别人的代码,接触到一个插件,before-after-...
    99+
    2022-12-15
    JavaScript before-after-hook钩子函数 JavaScript before-after-hook JavaScript 钩子函数
  • Vue中callHook钩子函数的作用是什么
    这期内容当中小编将会给大家带来有关Vue中callHook钩子函数的作用是什么,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。Vue实例在不同的生命周期阶段,都调用了cal...
    99+
    2022-10-19
  • c语言钩子函数的作用是什么
    C语言钩子函数的作用是用于在程序运行过程中拦截、修改或扩展特定事件的处理。钩子函数可以被用于监控、调试、记录或改变程序的行为。具体来...
    99+
    2023-09-29
    c语言
  • python钩子函数的作用有哪些
    Python钩子函数的作用有以下几个: 在特定事件发生时触发执行。钩子函数可以在特定事件发生时被调用,比如在程序启动、关闭、异常...
    99+
    2023-10-24
    python
  • Vue中钩子函数有什么用
    这篇文章给大家分享的是有关Vue中钩子函数有什么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。Vue-Router导航守卫有的时候,我们需要通过路由来进行一些操作,比如最常见的...
    99+
    2022-10-19
  • c语言钩子函数的用法是什么
    在C语言中,钩子函数(hook function)是一种特殊的函数,用于在程序执行过程中拦截、修改或扩展某些特定的操作。 钩子函数的...
    99+
    2023-10-24
    c语言
  • Vue中钩子函数怎么用
    小编给大家分享一下Vue中钩子函数怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!在Vue 中可以把一系列复杂的操作包装为一...
    99+
    2022-10-19
  • vue中的生命周期和钩子函数是什么
    这篇文章主要讲解了“vue中的生命周期和钩子函数是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“vue中的生命周期和钩子函数是什么”吧!1.什么是生命周期Vue 实例有一个完整的生命周期...
    99+
    2023-06-21
  • vue生命周期钩子函数是什么
    本篇内容主要讲解“vue生命周期钩子函数是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue生命周期钩子函数是什么”吧!vue生命周期钩子函数vue生命周期即为一个组件从出生到死亡的一个完...
    99+
    2023-06-30
  • vue-router中的钩子函数和执行顺序是什么
    这篇文章主要讲解了“vue-router中的钩子函数和执行顺序是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“vue-router中的钩子函数和执行顺序是什么”吧!一:全局导航钩子函数1...
    99+
    2023-07-02
  • Vue中callHook钩子函数怎么调用
    这篇“Vue中callHook钩子函数怎么调用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Vue中callHook钩子函数...
    99+
    2023-07-04
  • MFC键盘钩子事件的作用是什么
    MFC键盘钩子事件的作用是在Windows操作系统中拦截并处理键盘事件。通过使用MFC键盘钩子事件,可以监视和响应键盘输入,可以用于...
    99+
    2023-09-28
    MFC
  • TP框架中的钩子有什么作用
    这篇文章主要介绍“TP框架中的钩子有什么作用”,在日常操作中,相信很多人在TP框架中的钩子有什么作用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”TP框架中的钩子有什么作用”的疑惑有所帮助!接下来,请跟着小编...
    99+
    2023-06-25
  • python中timedelta函数的作用是什么
    今天就跟大家聊聊有关python中timedelta函数的作用是什么,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。python是什么意思Python是一种跨平台的、具有解释性、编译性...
    99+
    2023-06-14
  • python中len函数的作用是什么
    这篇文章将为大家详细讲解有关python中len函数的作用是什么,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。Python的优点有哪些1、简单易用,与C/C++、Java、C# 等传统语言相...
    99+
    2023-06-14
  • python中str函数的作用是什么
    python中str函数的作用是什么?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。python的数据类型有哪些python的数据类型:1. 数字类型,包括int(整型)、lon...
    99+
    2023-06-14
  • python中 ReLU函数的作用是什么
    python中 ReLU函数的作用是什么,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。1、说明线性整流函数,又称为修正性线性单元,ReLU是一个分段函数,其公式...
    99+
    2023-06-15
  • python中Tanh函数的作用是什么
    python中Tanh函数的作用是什么,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。1、说明Tanh是双曲函数中的一个,Tanh()为双曲正切。在数学中,双曲正切Tanh是由基...
    99+
    2023-06-15
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作