日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
5分鐘掌握Python中的Hook鉤子函數(shù)

 1. 什么是Hook

公司主營(yíng)業(yè)務(wù):成都網(wǎng)站建設(shè)、網(wǎng)站制作、移動(dòng)網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競(jìng)爭(zhēng)能力。成都創(chuàng)新互聯(lián)公司是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來(lái)的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來(lái)驚喜。成都創(chuàng)新互聯(lián)公司推出潁泉免費(fèi)做網(wǎng)站回饋大家。

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

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

從上面可知

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

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

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

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

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

  •  需要再插入隊(duì)列前,對(duì)數(shù)據(jù)進(jìn)行篩選 input_filter_fn
  •  插入隊(duì)列 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. ## 實(shí)現(xiàn)一個(gè)你所需要的鉤子實(shí)現(xiàn):比如如果content 包含time就過(guò)濾掉,否則插入隊(duì)列  
  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ù)的實(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)的淋漓盡致。

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

  •  開始訓(xùn)練
  •  訓(xùn)練一個(gè)epoch前
  •  訓(xùn)練一個(gè)batch前
  •  訓(xùn)練一個(gè)batch后
  •  訓(xùn)練一個(gè)epoch后
  •  評(píng)估驗(yàn)證集
  •  結(jié)束訓(xùn)練

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

keras中是通過(guò)各種回調(diào)函數(shù)來(lái)實(shí)現(xiàn)鉤子hook功能的。這里放一個(gè)callback的父類,定制時(shí)只要繼承這個(gè)父類,實(shí)現(xiàn)你過(guò)關(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是一個(gè)目標(biāo)檢測(cè)的開源框架,集成了許多不同的目標(biāo)檢測(cè)深度學(xué)習(xí)算法(pytorch版),如faster-rcnn, fpn, retianet等。里面也大量使用了hook,暴露給應(yīng)用實(shí)現(xiàn)流程中具體部分。

詳見(jiàn)https://github.com/open-mmlab/mmdetection

這里看一個(gè)訓(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的實(shí)現(xiàn)細(xì)則。希望對(duì)比有幫助。總結(jié)如下:

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

本文標(biāo)題:5分鐘掌握Python中的Hook鉤子函數(shù)
路徑分享:http://www.dlmjj.cn/article/cogcdcg.html