自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

5分鐘掌握Python中的Hook鉤子函數(shù)

開發(fā) 后端
本文介紹了hook的概念和應(yīng)用,并給出了python的實現(xiàn)細則。希望對比有幫助。

[[355003]]

 1. 什么是Hook

經(jīng)常會聽到鉤子函數(shù)(hook function)這個概念,最近在看目標(biāo)檢測開源框架mmdetection,里面也出現(xiàn)大量Hook的編程方式,那到底什么是hook?hook的作用是什么?

  •  what is hook ?鉤子hook,顧名思義,可以理解是一個掛鉤,作用是有需要的時候掛一個東西上去。具體的解釋是:鉤子函數(shù)是把我們自己實現(xiàn)的hook函數(shù)在某一時刻掛接到目標(biāo)掛載點上。
  •  hook函數(shù)的作用 舉個例子,hook的概念在windows桌面軟件開發(fā)很常見,特別是各種事件觸發(fā)的機制; 比如C++的MFC程序中,要監(jiān)聽鼠標(biāo)左鍵按下的時間,MFC提供了一個onLeftKeyDown的鉤子函數(shù)。很顯然,MFC框架并沒有為我們實現(xiàn)onLeftKeyDown具體的操作,只是為我們提供一個鉤子,當(dāng)我們需要處理的時候,只要去重寫這個函數(shù),把我們需要操作掛載在這個鉤子里,如果我們不掛載,MFC事件觸發(fā)機制中執(zhí)行的就是空的操作。

從上面可知

  •  hook函數(shù)是程序中預(yù)定義好的函數(shù),這個函數(shù)處于原有程序流程當(dāng)中(暴露一個鉤子出來)
  •  我們需要再在有流程中鉤子定義的函數(shù)塊中實現(xiàn)某個具體的細節(jié),需要把我們的實現(xiàn),掛接或者注冊(register)到鉤子里,使得hook函數(shù)對目標(biāo)可用
  •  hook 是一種編程機制,和具體的語言沒有直接的關(guān)系
  •  如果從設(shè)計模式上看,hook模式是模板方法的擴展
  •  鉤子只有注冊的時候,才會使用,所以原有程序的流程中,沒有注冊或掛載時,執(zhí)行的是空(即沒有執(zhí)行任何操作)

本文用python來解釋hook的實現(xiàn)方式,并展示在開源項目中hook的應(yīng)用案例。hook函數(shù)和我們常聽到另外一個名稱:回調(diào)函數(shù)(callback function)功能是類似的,可以按照同種模式來理解。

[[355004]]

2. hook實現(xiàn)例子

據(jù)我所知,hook函數(shù)最常使用在某種流程處理當(dāng)中。這個流程往往有很多步驟。hook函數(shù)常常掛載在這些步驟中,為增加額外的一些操作,提供靈活性。

下面舉一個簡單的例子,這個例子的目的是實現(xiàn)一個通用往隊列中插入內(nèi)容的功能。流程步驟有2個

  •  需要再插入隊列前,對數(shù)據(jù)進行篩選 input_filter_fn
  •  插入隊列 insert_queue 
  1. class ContentStash(object):  
  2.     """  
  3.     content stash for online operation  
  4.     pipeline is  
  5.     1. input_filter: filter some contents, no use to user  
  6.     2. insert_queue(redis or other broker): insert useful content to queue  
  7.     """  
  8.     def __init__(self):  
  9.         self.input_filter_fn = None  
  10.         self.broker = []  
  11.     def register_input_filter_hook(self, input_filter_fn):  
  12.         """  
  13.         register input filter function, parameter is content dict  
  14.         Args:  
  15.             input_filter_fn: input filter function  
  16.         Returns:  
  17.         """  
  18.         self.input_filter_fn = input_filter_fn  
  19.     def insert_queue(self, content):  
  20.         """  
  21.         insert content to queue  
  22.         Args:  
  23.             content: dict 
  24.         Returns: 
  25.         """  
  26.         self.broker.append(content)  
  27.     def input_pipeline(self, content, use=False):  
  28.         """  
  29.         pipeline of input for content stash  
  30.         Args:  
  31.             use: is use, defaul False  
  32.             content: dict 
  33.         Returns:  
  34.         """  
  35.         if not use:  
  36.             return  
  37.         # input filter  
  38.         if self.input_filter_fn:  
  39.             _filter = self.input_filter_fn(content)         
  40.          # insert to queue 
  41.         if not _filter:  
  42.             self.insert_queue(content)  
  43.  # test  
  44. ## 實現(xiàn)一個你所需要的鉤子實現(xiàn):比如如果content 包含time就過濾掉,否則插入隊列  
  45. def input_filter_hook(content):  
  46.     """  
  47.     test input filter hook  
  48.     Args:  
  49.         content: dict  
  50.     Returns: None or content  
  51.     """  
  52.     if content.get('time') is None:  
  53.         return  
  54.     else:  
  55.         return content  
  56. # 原有程序  
  57. content = {'filename': 'test.jpg', 'b64_file': "#test", 'data': {"result": "cat", "probility": 0.9}}  
  58. content_stash = ContentStash('audit', work_dir='' 
  59. # 掛上鉤子函數(shù), 可以有各種不同鉤子函數(shù)的實現(xiàn),但是要主要函數(shù)輸入輸出必須保持原有程序中一致,比如這里是content  
  60. content_stash.register_input_filter_hook(input_filter_hook)  
  61. # 執(zhí)行流程  
  62. content_stash.input_pipeline(content) 

3. hook在開源框架中的應(yīng)用

3.1 keras

在深度學(xué)習(xí)訓(xùn)練流程中,hook函數(shù)體現(xiàn)的淋漓盡致。

一個訓(xùn)練過程(不包括數(shù)據(jù)準(zhǔn)備),會輪詢多次訓(xùn)練集,每次稱為一個epoch,每個epoch又分為多個batch來訓(xùn)練。流程先后拆解成:

  •  開始訓(xùn)練
  •  訓(xùn)練一個epoch前
  •  訓(xùn)練一個batch前
  •  訓(xùn)練一個batch后
  •  訓(xùn)練一個epoch后
  •  評估驗證集
  •  結(jié)束訓(xùn)練

這些步驟是穿插在訓(xùn)練一個batch數(shù)據(jù)的過程中,這些可以理解成是鉤子函數(shù),我們可能需要在這些鉤子函數(shù)中實現(xiàn)一些定制化的東西,比如在訓(xùn)練一個epoch后我們要保存下訓(xùn)練的模型,在結(jié)束訓(xùn)練時用最好的模型執(zhí)行下測試集的效果等等。

keras中是通過各種回調(diào)函數(shù)來實現(xiàn)鉤子hook功能的。這里放一個callback的父類,定制時只要繼承這個父類,實現(xiàn)你過關(guān)注的鉤子就可以了。 

  1. @keras_export('keras.callbacks.Callback')  
  2. class Callback(object):  
  3.   """Abstract base class used to build new callbacks.  
  4.   Attributes:  
  5.       params: Dict. Training parameters  
  6.           (eg. verbosity, batch size, number of epochs...).  
  7.       model: Instance of `keras.models.Model`.  
  8.           Reference of the model being trained.  
  9.   The `logs` dictionary that callback methods  
  10.   take as argument will contain keys for quantities relevant to  
  11.   the current batch or epoch (see method-specific docstrings).  
  12.   """  
  13.   def __init__(self):  
  14.     self.validation_data = None  # pylint: disable=g-missing-from-attributes  
  15.     self.model = None  
  16.     # Whether this Callback should only run on the chief worker in a  
  17.     # Multi-Worker setting.  
  18.     # TODO(omalleyt): Make this attr public once solution is stable.  
  19.     self._chief_worker_only = None  
  20.     self._supports_tf_logs = False  
  21.   def set_params(self, params):  
  22.     self.params = params  
  23.   def set_model(self, model):  
  24.     self.model = model  
  25.   @doc_controls.for_subclass_implementers  
  26.   @generic_utils.default  
  27.   def on_batch_begin(self, batch, logs=None):  
  28.     """A backwards compatibility alias for `on_train_batch_begin`."""  
  29.   @doc_controls.for_subclass_implementers  
  30.   @generic_utils.default  
  31.   def on_batch_end(self, batch, logs=None):  
  32.     """A backwards compatibility alias for `on_train_batch_end`."""  
  33.   @doc_controls.for_subclass_implementers  
  34.   def on_epoch_begin(self, epoch, logs=None):  
  35.     """Called at the start of an epoch.   
  36.     Subclasses should override for any actions to run. This function should only  
  37.     be called during TRAIN mode. 
  38.     Arguments:  
  39.         epoch: Integer, index of epoch.  
  40.         logs: Dict. Currently no data is passed to this argument for this method  
  41.           but that may change in the future.  
  42.     """  
  43.   @doc_controls.for_subclass_implementers  
  44.   def on_epoch_end(self, epoch, logs=None):  
  45.     """Called at the end of an epoch.  
  46.     Subclasses should override for any actions to run. This function should only  
  47.     be called during TRAIN mode.  
  48.     Arguments:  
  49.         epoch: Integer, index of epoch.  
  50.         logs: Dict, metric results for this training epoch, and for the  
  51.           validation epoch if validation is performed. Validation result keys  
  52.           are prefixed with `val_`. 
  53.      """ 
  54.   @doc_controls.for_subclass_implementers  
  55.   @generic_utils.default  
  56.   def on_train_batch_begin(self, batch, logs=None):  
  57.     """Called at the beginning of a training batch in `fit` methods.  
  58.     Subclasses should override for any actions to run.  
  59.     Arguments:  
  60.         batch: Integer, index of batch within the current epoch.  
  61.         logs: Dict, contains the return value of `model.train_step`. Typically,  
  62.           the values of the `Model`'s metrics are returned.  Example:  
  63.           `{'loss': 0.2, 'accuracy': 0.7}`.  
  64.     """  
  65.     # For backwards compatibility.  
  66.     self.on_batch_begin(batch, logslogs=logs)  
  67.   @doc_controls.for_subclass_implementers  
  68.   @generic_utils.default  
  69.   def on_train_batch_end(self, batch, logs=None):  
  70.     """Called at the end of a training batch in `fit` methods.  
  71.     Subclasses should override for any actions to run.  
  72.     Arguments:  
  73.         batch: Integer, index of batch within the current epoch.  
  74.         logs: Dict. Aggregated metric results up until this batch.  
  75.     """  
  76.     # For backwards compatibility.  
  77.     self.on_batch_end(batch, logslogs=logs)  
  78.   @doc_controls.for_subclass_implementers  
  79.   @generic_utils.default  
  80.   def on_test_batch_begin(self, batch, logs=None):  
  81.     """Called at the beginning of a batch in `evaluate` methods.  
  82.     Also called at the beginning of a validation batch in the `fit`  
  83.     methods, if validation data is provided.  
  84.     Subclasses should override for any actions to run.  
  85.     Arguments:  
  86.         batch: Integer, index of batch within the current epoch.  
  87.         logs: Dict, contains the return value of `model.test_step`. Typically,  
  88.           the values of the `Model`'s metrics are returned.  Example:  
  89.           `{'loss': 0.2, 'accuracy': 0.7}`.  
  90.     """  
  91.   @doc_controls.for_subclass_implementers  
  92.   @generic_utils.default  
  93.   def on_test_batch_end(self, batch, logs=None):  
  94.     """Called at the end of a batch in `evaluate` methods.  
  95.     Also called at the end of a validation batch in the `fit`  
  96.     methods, if validation data is provided.  
  97.     Subclasses should override for any actions to run.  
  98.     Arguments:  
  99.         batch: Integer, index of batch within the current epoch.  
  100.         logs: Dict. Aggregated metric results up until this batch.  
  101.     """  
  102.   @doc_controls.for_subclass_implementers  
  103.   @generic_utils.default  
  104.   def on_predict_batch_begin(self, batch, logs=None):  
  105.     """Called at the beginning of a batch in `predict` methods.  
  106.     Subclasses should override for any actions to run.  
  107.     Arguments:  
  108.         batch: Integer, index of batch within the current epoch.  
  109.         logs: Dict, contains the return value of `model.predict_step`,  
  110.           it typically returns a dict with a key 'outputs' containing  
  111.           the model's outputs.  
  112.     """ 
  113.   @doc_controls.for_subclass_implementers  
  114.   @generic_utils.default  
  115.   def on_predict_batch_end(self, batch, logs=None):  
  116.     """Called at the end of a batch in `predict` methods.  
  117.     Subclasses should override for any actions to run.  
  118.     Arguments:  
  119.         batch: Integer, index of batch within the current epoch.  
  120.         logs: Dict. Aggregated metric results up until this batch.  
  121.     """ 
  122.   @doc_controls.for_subclass_implementers  
  123.   def on_train_begin(self, logs=None):  
  124.     """Called at the beginning of training.   
  125.     Subclasses should override for any actions to run.  
  126.     Arguments:  
  127.         logs: Dict. Currently no data is passed to this argument for this method  
  128.           but that may change in the future.  
  129.     """  
  130.   @doc_controls.for_subclass_implementers  
  131.   def on_train_end(self, logs=None):  
  132.     """Called at the end of training.   
  133.     Subclasses should override for any actions to run.  
  134.     Arguments:  
  135.         logs: Dict. Currently the output of the last call to `on_epoch_end()`  
  136.           is passed to this argument for this method but that may change in  
  137.           the future.  
  138.     """ 
  139.   @doc_controls.for_subclass_implementers  
  140.   def on_test_begin(self, logs=None):  
  141.     """Called at the beginning of evaluation or validation.  
  142.     Subclasses should override for any actions to run.  
  143.     Arguments:  
  144.         logs: Dict. Currently no data is passed to this argument for this method  
  145.           but that may change in the future.  
  146.     """  
  147.   @doc_controls.for_subclass_implementers  
  148.   def on_test_end(self, logs=None):  
  149.     """Called at the end of evaluation or validation.  
  150.     Subclasses should override for any actions to run.  
  151.     Arguments:  
  152.         logs: Dict. Currently the output of the last call to  
  153.           `on_test_batch_end()` is passed to this argument for this method  
  154.           but that may change in the future.  
  155.     """  
  156.   @doc_controls.for_subclass_implementers  
  157.   def on_predict_begin(self, logs=None): 
  158.      """Called at the beginning of prediction. 
  159.     Subclasses should override for any actions to run.  
  160.     Arguments:  
  161.         logs: Dict. Currently no data is passed to this argument for this method  
  162.           but that may change in the future.  
  163.     """ 
  164.   @doc_controls.for_subclass_implementers  
  165.   def on_predict_end(self, logs=None):  
  166.     """Called at the end of prediction.  
  167.     Subclasses should override for any actions to run.  
  168.     Arguments: 
  169.          logs: Dict. Currently no data is passed to this argument for this method  
  170.           but that may change in the future.  
  171.     """  
  172.   def _implements_train_batch_hooks(self):  
  173.     """Determines if this Callback should be called for each train batch."""  
  174.     return (not generic_utils.is_default(self.on_batch_begin) or  
  175.             not generic_utils.is_default(self.on_batch_end) or  
  176.             not generic_utils.is_default(self.on_train_batch_begin) or  
  177.             not generic_utils.is_default(self.on_train_batch_end)) 

這些鉤子的原始程序是在模型訓(xùn)練流程中的

keras源碼位置: tensorflow\python\keras\engine\training.py

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

  1. # Container that configures and calls `tf.keras.Callback`s.  
  2.       if not isinstance(callbacks, callbacks_module.CallbackList):  
  3.         callbacks = callbacks_module.CallbackList(  
  4.             callbacks,  
  5.             add_history=True 
  6.             add_progbar=verbose != 0,  
  7.             model=self 
  8.             verboseverbose=verbose,  
  9.             epochsepochs=epochs,  
  10.             steps=data_handler.inferred_steps)  
  11.       ## I am hook  
  12.       callbacks.on_train_begin()  
  13.       training_logs = None  
  14.       # Handle fault-tolerance for multi-worker.  
  15.       # TODO(omalleyt): Fix the ordering issues that mean this has to  
  16.       # happen after `callbacks.on_train_begin`.  
  17.       data_handler._initial_epoch = (  # pylint: disable=protected-access  
  18.           self._maybe_load_initial_epoch_from_ckpt(initial_epoch))  
  19.       for epoch, iterator in data_handler.enumerate_epochs():  
  20.         self.reset_metrics()  
  21.         callbacks.on_epoch_begin(epoch)  
  22.         with data_handler.catch_stop_iteration():  
  23.           for step in data_handler.steps():  
  24.             with trace.Trace(  
  25.                 'TraceContext',  
  26.                 graph_type='train' 
  27.                 epochepoch_num=epoch, 
  28.                  stepstep_num=step,  
  29.                 batch_sizebatch_size=batch_size):  
  30.               ## I am hook  
  31.               callbacks.on_train_batch_begin(step)  
  32.               tmp_logs = train_function(iterator)  
  33.               if data_handler.should_sync:  
  34.                 context.async_wait()  
  35.               logs = tmp_logs  # No error, now safe to assign to logs.  
  36.               end_step = step + data_handler.step_increment  
  37.               callbacks.on_train_batch_end(end_step, logs)  
  38.         epoch_logs = copy.copy(logs)  
  39.         # Run validation.  
  40.         ## I am hook 
  41.          callbacks.on_epoch_end(epoch, epoch_logs) 

3.2 mmdetection

mmdetection是一個目標(biāo)檢測的開源框架,集成了許多不同的目標(biāo)檢測深度學(xué)習(xí)算法(pytorch版),如faster-rcnn, fpn, retianet等。里面也大量使用了hook,暴露給應(yīng)用實現(xiàn)流程中具體部分。

詳見https://github.com/open-mmlab/mmdetection

這里看一個訓(xùn)練的調(diào)用例子(摘錄)(https://github.com/open-mmlab/mmdetection/blob/5d592154cca589c5113e8aadc8798bbc73630d98/mmdet/apis/train.py) 

  1. def train_detector(model,  
  2.                    dataset,  
  3.                    cfg,  
  4.                    distributed=False 
  5.                    validate=False 
  6.                    timestamp=None 
  7.                    meta=None):  
  8.     logger = get_root_logger(cfg.log_level)  
  9.     # prepare data loaders  
  10.     # put model on gpus  
  11.     # build runner  
  12.     optimizer = build_optimizer(model, cfg.optimizer)  
  13.     runner = EpochBasedRunner 
  14.         model,  
  15.         optimizeroptimizer=optimizer,  
  16.         work_dir=cfg.work_dir,  
  17.         loggerlogger=logger,  
  18.         metameta=meta)  
  19.     # an ugly workaround to make .log and .log.json filenames the same  
  20.     runner.timestamp = timestamp  
  21.     # fp16 setting  
  22.     # register hooks  
  23.     runner.register_training_hooks(cfg.lr_config, optimizer_config,  
  24.                                    cfg.checkpoint_config, cfg.log_config,  
  25.                                    cfg.get('momentum_config', None))  
  26.     if distributed:  
  27.         runner.register_hook(DistSamplerSeedHook())  
  28.     # register eval hooks  
  29.     if validate:  
  30.         # Support batch_size > 1 in validation  
  31.         eval_cfg = cfg.get('evaluation', {})  
  32.         eval_hook = DistEvalHook if distributed else EvalHook  
  33.         runner.register_hook(eval_hook(val_dataloader, **eval_cfg))  
  34.     # user-defined hooks  
  35.     if cfg.get('custom_hooks', None):  
  36.         custom_hooks = cfg.custom_hooks  
  37.         assert isinstance(custom_hooks, list), \  
  38.             f'custom_hooks expect list type, but got {type(custom_hooks)}'  
  39.         for hook_cfg in cfg.custom_hooks:  
  40.             assert isinstance(hook_cfg, dict), \  
  41.                 'Each item in custom_hooks expects dict type, but got ' \  
  42.                 f'{type(hook_cfg)}'  
  43.             hook_cfghook_cfg = hook_cfg.copy()  
  44.             priority = hook_cfg.pop('priority', 'NORMAL')  
  45.             hook = build_from_cfg(hook_cfg, HOOKS)  
  46.             runner.register_hook(hook, prioritypriority=priority) 

4. 總結(jié)

本文介紹了hook的概念和應(yīng)用,并給出了python的實現(xiàn)細則。希望對比有幫助??偨Y(jié)如下:

  •  hook函數(shù)是流程中預(yù)定義好的一個步驟,沒有實現(xiàn)
  •  掛載或者注冊時, 流程執(zhí)行就會執(zhí)行這個鉤子函數(shù)
  •  回調(diào)函數(shù)和hook函數(shù)功能上是一致的
  •  hook設(shè)計方式帶來靈活性,如果流程中有一個步驟,你想讓調(diào)用方來實現(xiàn),你可以用hook函數(shù) 

 

責(zé)任編輯:龐桂玉 來源: Python中文社區(qū)(ID:python-china)
相關(guān)推薦

2020-12-17 10:00:16

Python協(xié)程線程

2021-03-12 09:45:00

Python關(guān)聯(lián)規(guī)則算法

2021-01-29 11:25:57

Python爬山算法函數(shù)優(yōu)化

2020-11-24 11:50:52

Python文件代碼

2020-12-07 11:23:32

Scrapy爬蟲Python

2021-03-23 15:35:36

Adam優(yōu)化語言

2017-01-10 09:07:53

tcpdumpGET請求

2023-06-19 08:23:28

kubernetes容器

2020-05-06 10:10:51

Python代碼鏈?zhǔn)秸{(diào)用

2020-10-27 10:43:24

Redis字符串數(shù)據(jù)庫

2018-01-30 05:04:06

2018-03-06 14:37:58

數(shù)據(jù)庫MongoDBregex

2021-06-07 09:51:22

原型模式序列化

2009-11-17 14:50:50

Oracle調(diào)優(yōu)

2020-09-11 09:35:18

前端JavaScript策略模式

2021-04-19 23:29:44

MakefilemacOSLinux

2021-01-11 09:33:37

Maven數(shù)目項目

2019-07-24 15:29:55

JavaScript開發(fā) 技巧

2018-11-28 11:20:53

Python函數(shù)式編程編程語言

2012-06-28 10:26:51

Silverlight
點贊
收藏

51CTO技術(shù)棧公眾號