欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

tensorflow estimator 使用hook實(shí)現(xiàn)finetune方式

 更新時(shí)間:2020年01月21日 09:43:47   作者:andylei777  
今天小編就為大家分享一篇tensorflow estimator 使用hook實(shí)現(xiàn)finetune方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

為了實(shí)現(xiàn)finetune有如下兩種解決方案:

model_fn里面定義好模型之后直接賦值

 def model_fn(features, labels, mode, params):
 # .....
 # finetune
 if params.checkpoint_path and (not tf.train.latest_checkpoint(params.model_dir)):
 checkpoint_path = None
 if tf.gfile.IsDirectory(params.checkpoint_path):
  checkpoint_path = tf.train.latest_checkpoint(params.checkpoint_path)
 else:
  checkpoint_path = params.checkpoint_path

 tf.train.init_from_checkpoint(
  ckpt_dir_or_file=checkpoint_path,
  assignment_map={params.checkpoint_scope: params.checkpoint_scope} # 'OptimizeLoss/':'OptimizeLoss/'
 )

使用鉤子 hooks。

可以在定義tf.contrib.learn.Experiment的時(shí)候通過(guò)train_monitors參數(shù)指定

 # Define the experiment
 experiment = tf.contrib.learn.Experiment(
 estimator=estimator, # Estimator
 train_input_fn=train_input_fn, # First-class function
 eval_input_fn=eval_input_fn, # First-class function
 train_steps=params.train_steps, # Minibatch steps
 min_eval_frequency=params.eval_min_frequency, # Eval frequency
 # train_monitors=[], # Hooks for training
 # eval_hooks=[eval_input_hook], # Hooks for evaluation
 eval_steps=params.eval_steps # Use evaluation feeder until its empty
 )

也可以在定義tf.estimator.EstimatorSpec 的時(shí)候通過(guò)training_chief_hooks參數(shù)指定。

不過(guò)個(gè)人覺(jué)得最好還是在estimator中定義,讓experiment只專注于控制實(shí)驗(yàn)的模式(訓(xùn)練次數(shù),驗(yàn)證次數(shù)等等)。

def model_fn(features, labels, mode, params):

 # ....

 return tf.estimator.EstimatorSpec(
 mode=mode,
 predictions=predictions,
 loss=loss,
 train_op=train_op,
 eval_metric_ops=eval_metric_ops,
 # scaffold=get_scaffold(),
 # training_chief_hooks=None
 )

這里順便解釋以下tf.estimator.EstimatorSpec對(duì)像的作用。該對(duì)象描述來(lái)一個(gè)模型的方方面面。包括:

當(dāng)前的模式:

mode: A ModeKeys. Specifies if this is training, evaluation or prediction.

計(jì)算圖

predictions: Predictions Tensor or dict of Tensor.

loss: Training loss Tensor. Must be either scalar, or with shape [1].

train_op: Op for the training step.

eval_metric_ops: Dict of metric results keyed by name. The values of the dict are the results of calling a metric function, namely a (metric_tensor, update_op) tuple. metric_tensor should be evaluated without any impact on state (typically is a pure computation results based on variables.). For example, it should not trigger the update_op or requires any input fetching.

導(dǎo)出策略

export_outputs: Describes the output signatures to be exported to

SavedModel and used during serving. A dict {name: output} where:

name: An arbitrary name for this output.

output: an ExportOutput object such as ClassificationOutput, RegressionOutput, or PredictOutput. Single-headed models only need to specify one entry in this dictionary. Multi-headed models should specify one entry for each head, one of which must be named using signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY.

chief鉤子 訓(xùn)練時(shí)的模型保存策略鉤子CheckpointSaverHook, 模型恢復(fù)等

training_chief_hooks: Iterable of tf.train.SessionRunHook objects to run on the chief worker during training.

worker鉤子 訓(xùn)練時(shí)的監(jiān)控策略鉤子如: NanTensorHook LoggingTensorHook 等

training_hooks: Iterable of tf.train.SessionRunHook objects to run on all workers during training.

指定初始化和saver

scaffold: A tf.train.Scaffold object that can be used to set initialization, saver, and more to be used in training.

evaluation鉤子

evaluation_hooks: Iterable of tf.train.SessionRunHook objects to run during evaluation.

自定義的鉤子如下:

class RestoreCheckpointHook(tf.train.SessionRunHook):
 def __init__(self,
   checkpoint_path,
   exclude_scope_patterns,
   include_scope_patterns
   ):
 tf.logging.info("Create RestoreCheckpointHook.")
 #super(IteratorInitializerHook, self).__init__()
 self.checkpoint_path = checkpoint_path

 self.exclude_scope_patterns = None if (not exclude_scope_patterns) else exclude_scope_patterns.split(',')
 self.include_scope_patterns = None if (not include_scope_patterns) else include_scope_patterns.split(',')


 def begin(self):
 # You can add ops to the graph here.
 print('Before starting the session.')

 # 1. Create saver

 #exclusions = []
 #if self.checkpoint_exclude_scopes:
 # exclusions = [scope.strip()
 #  for scope in self.checkpoint_exclude_scopes.split(',')]
 #
 #variables_to_restore = []
 #for var in slim.get_model_variables(): #tf.global_variables():
 # excluded = False
 # for exclusion in exclusions:
 # if var.op.name.startswith(exclusion):
 # excluded = True
 # break
 # if not excluded:
 # variables_to_restore.append(var)
 #inclusions
 #[var for var in tf.trainable_variables() if var.op.name.startswith('InceptionResnetV1')]

 variables_to_restore = tf.contrib.framework.filter_variables(
  slim.get_model_variables(),
  include_patterns=self.include_scope_patterns, # ['Conv'],
  exclude_patterns=self.exclude_scope_patterns, # ['biases', 'Logits'],

  # If True (default), performs re.search to find matches
  # (i.e. pattern can match any substring of the variable name).
  # If False, performs re.match (i.e. regexp should match from the beginning of the variable name).
  reg_search = True
 )
 self.saver = tf.train.Saver(variables_to_restore)


 def after_create_session(self, session, coord):
 # When this is called, the graph is finalized and
 # ops can no longer be added to the graph.

 print('Session created.')

 tf.logging.info('Fine-tuning from %s' % self.checkpoint_path)
 self.saver.restore(session, os.path.expanduser(self.checkpoint_path))
 tf.logging.info('End fineturn from %s' % self.checkpoint_path)

 def before_run(self, run_context):
 #print('Before calling session.run().')
 return None #SessionRunArgs(self.your_tensor)

 def after_run(self, run_context, run_values):
 #print('Done running one step. The value of my tensor: %s', run_values.results)
 #if you-need-to-stop-loop:
 # run_context.request_stop()
 pass


 def end(self, session):
 #print('Done with the session.')
 pass

以上這篇tensorflow estimator 使用hook實(shí)現(xiàn)finetune方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python語(yǔ)言實(shí)現(xiàn)機(jī)器學(xué)習(xí)的K-近鄰算法

    Python語(yǔ)言實(shí)現(xiàn)機(jī)器學(xué)習(xí)的K-近鄰算法

    今天學(xué)習(xí)的算法是KNN近鄰算法。KNN算法是一個(gè)監(jiān)督學(xué)習(xí)分類器類別的算法。下面我們來(lái)詳細(xì)的探討下
    2015-06-06
  • opencv導(dǎo)入頭文件時(shí)報(bào)錯(cuò)#include的解決方法

    opencv導(dǎo)入頭文件時(shí)報(bào)錯(cuò)#include的解決方法

    這篇文章主要介紹了opencv導(dǎo)入頭文件時(shí)報(bào)錯(cuò)#include的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • 淺談對(duì)yield的初步理解

    淺談對(duì)yield的初步理解

    下面小編就為大家?guī)?lái)一篇淺談對(duì)yield的初步理解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-05-05
  • Python數(shù)據(jù)集庫(kù)Vaex秒開(kāi)100GB加數(shù)據(jù)

    Python數(shù)據(jù)集庫(kù)Vaex秒開(kāi)100GB加數(shù)據(jù)

    這篇文章主要為大家介紹了Python數(shù)據(jù)集庫(kù)Vaex秒開(kāi)100GB加數(shù)據(jù)實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • Python中的with...as用法介紹

    Python中的with...as用法介紹

    這篇文章主要介紹了Python中的with...as用法介紹,本文直接給出用法實(shí)例,需要的朋友可以參考下
    2015-05-05
  • Python+matplotlib實(shí)現(xiàn)簡(jiǎn)單曲線的繪制

    Python+matplotlib實(shí)現(xiàn)簡(jiǎn)單曲線的繪制

    Matplotlib是Python的繪圖庫(kù),它能讓使用者很輕松地將數(shù)據(jù)圖形化,并且提供多樣化的輸出格式。本文將利用matplotlib繪制簡(jiǎn)單的曲線圖,感興趣的朋友可以學(xué)習(xí)一下
    2022-04-04
  • 實(shí)例講解Python中SocketServer模塊處理網(wǎng)絡(luò)請(qǐng)求的用法

    實(shí)例講解Python中SocketServer模塊處理網(wǎng)絡(luò)請(qǐng)求的用法

    SocketServer模塊中帶有很多實(shí)現(xiàn)服務(wù)器所能夠用到的socket類和操作方法,下面我們就來(lái)以實(shí)例講解Python中SocketServer模塊處理網(wǎng)絡(luò)請(qǐng)求的用法:
    2016-06-06
  • 詳解PyCharm安裝MicroPython插件的教程

    詳解PyCharm安裝MicroPython插件的教程

    PyCharm可以說(shuō)是當(dāng)今最流行的一款Python IDE了,大部分購(gòu)買TPYBoard的小伙伴都會(huì)使用PyCharm編寫MicroPython的程序。這篇文章給大家介紹了PyCharm安裝MicroPython插件的教程,需要的朋友參考下吧
    2019-06-06
  • 利用Python讀取微信朋友圈的多種方法總結(jié)

    利用Python讀取微信朋友圈的多種方法總結(jié)

    這篇文章主要給大家介紹了關(guān)于如何利用Python讀取微信朋友圈的多種方法,對(duì)于一個(gè)新手來(lái)說(shuō)如果單獨(dú)的去爬取朋友圈的話,難度會(huì)非常大,可以借鑒這篇文章的內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • 在Python的setuptools框架下生成egg的教程

    在Python的setuptools框架下生成egg的教程

    這篇文章主要介紹了在Python的setuptools框架下生成egg的教程,本文來(lái)自于IBM官方開(kāi)發(fā)者技術(shù)文檔,需要的朋友可以參考下
    2015-04-04

最新評(píng)論