tensorflow estimator 使用hook实现finetune方式

为了实现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的时候通过train_monitors参数指定

 # 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 的时候通过training_chief_hooks参数指定。

不过个人觉得最好还是在estimator中定义,让experiment只专注于控制实验的模式(训练次数,验证次数等等)。

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对像的作用。该对象描述来一个模型的方方面面。包括:

当前的模式:

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

计算图

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.

导出策略

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钩子 训练时的模型保存策略钩子CheckpointSaverHook, 模型恢复等

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

worker钩子 训练时的监控策略钩子如: 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实现finetune方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Python通过TensorFLow进行线性模型训练原理与实现方法详解

    本文实例讲述了Python通过TensorFLow进行线性模型训练原理与实现方法.分享给大家供大家参考,具体如下: 1.相关概念 例如要从一个线性分布的途中抽象出其y=kx+b的分布规律 特征是输入变量,即简单线性回归中的 x 变量.简单的机器学习项目可能会使用单个特征,而比较复杂的机器学习项目可能会使用数百万个特征. 标签是我们要预测的事物,即简单线性回归中的 y 变量. 样本是指具体的数据实例.有标签样本是指具有{特征,标签}的数据,用于训练模型,总结规律.无标签样本只具有特征的数据x,通过

  • tensorflow实现对张量数据的切片操作方式

    如下所示: import tensorflow as tf a=tf.constant([[[1,2,3,4],[4,5,6,7],[7,8,9,10]], [[11,12,13,14],[20,21,22,23],[15,16,17,18]]]) print(a.shape) b,c=tf.split(a,2,0) #参数1.张量 2.获得的切片数 3.切片的维度 将两个切片分别赋值给b,c print(b.shape) print(c.shape with tf.Session() as s

  • 详解Tensorflow数据读取有三种方式(next_batch)

    Tensorflow数据读取有三种方式: Preloaded data: 预加载数据 Feeding: Python产生数据,再把数据喂给后端. Reading from file: 从文件中直接读取 这三种有读取方式有什么区别呢? 我们首先要知道TensorFlow(TF)是怎么样工作的. TF的核心是用C++写的,这样的好处是运行快,缺点是调用不灵活.而Python恰好相反,所以结合两种语言的优势.涉及计算的核心算子和运行框架是用C++写的,并提供API给Python.Python调用这些A

  • Pytorch之finetune使用详解

    finetune分为全局finetune和局部finetune.首先介绍一下局部finetune步骤: 1.固定参数 for name, child in model.named_children(): for param in child.parameters(): param.requires_grad = False 后,只传入 需要反传的参数,否则会报错 filter(lambda param: param.requires_grad, model.parameters()) 2.调低学

  • 利用Tensorflow构建和训练自己的CNN来做简单的验证码识别方式

    Tensorflow是目前最流行的深度学习框架,我们可以用它来搭建自己的卷积神经网络并训练自己的分类器,本文介绍怎样使用Tensorflow构建自己的CNN,怎样训练用于简单的验证码识别的分类器.本文假设你已经安装好了Tensorflow,了解过CNN的一些知识. 下面将分步介绍怎样获得训练数据,怎样使用tensorflow构建卷积神经网络,怎样训练,以及怎样测试训练出来的分类器 1. 准备训练样本 使用Python的库captcha来生成我们需要的训练样本,代码如下: import sys i

  • tensorflow estimator 使用hook实现finetune方式

    为了实现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.chec

  • Tensorflow轻松实现XOR运算的方式

    对于"XOR"大家应该都不陌生,我们在各种课程中都会遇到,它是一个数学逻辑运算符号,在计算机中表示为"XOR",在数学中表示为"",学名为"异或",其来源细节就不详细表明了,说白了就是两个a.b两个值做异或运算,若a=b则结果为0,反之为1,即"相同为0,不同为1". 在计算机早期发展中,逻辑运算广泛应用于电子管中,这一点如果大家学习过微机原理应该会比较熟悉,那么在神经网络中如何实现它呢,早先我们使用的是感

  • 利用Tensorflow的队列多线程读取数据方式

    在tensorflow中,有三种方式输入数据 1. 利用feed_dict送入numpy数组 2. 利用队列从文件中直接读取数据 3. 预加载数据 其中第一种方式很常用,在tensorflow的MNIST训练源码中可以看到,通过feed_dict={},可以将任意数据送入tensor中. 第二种方式相比于第一种,速度更快,可以利用多线程的优势把数据送入队列,再以batch的方式出队,并且在这个过程中可以很方便地对图像进行随机裁剪.翻转.改变对比度等预处理,同时可以选择是否对数据随机打乱,可以说是

  • 基于Tensorflow批量数据的输入实现方式

    基于Tensorflow下的批量数据的输入处理: 1.Tensor TFrecords格式 2.h5py的库的数组方法 在tensorflow的框架下写CNN代码,我在书写过程中,感觉不是框架内容难写, 更多的是我在对图像的预处理和输入这部分花了很多精神. 使用了两种方法: 方法一: Tensor 以Tfrecords的格式存储数据,如果对数据进行标签,可以同时做到数据打标签. ①创建TFrecords文件 orig_image = '/home/images/train_image/' gen

  • 使用TensorFlow直接获取处理MNIST数据方式

    MNIST是一个非常有名的手写体数字识别数据集,TensorFlow对MNIST数据集做了封装,可以直接调用.MNIST数据集包含了60000张图片作为训练数据,10000张图片作为测试数据,每一张图片都代表了0-9中的一个数字,图片大小都是28*28.虽然这个数据集只提供了训练和测试数据,但是为了验证训练网络的效果,一般从训练数据中划分出一部分数据作为验证数据,测试神经网络模型在不同参数下的效果.TensorFlow提供了一个类来处理MNIST数据. 代码如下: from tensorflow

  • Tensorflow tensor 数学运算和逻辑运算方式

    一.arthmetic 算术操作(+,-,*,/,Mod) (1)tensor-tensor操作(element-wise) #两个tensor 运算 #运算规则:element-wise.即c[i,j,..,k]=a[i,j,..,k] op b[i,j,..,k] ts1=tf.constant(1.0,shape=[2,2]) ts2=tf.Variable(tf.random_normal([2,2])) sess.run(tf.global_variables_initializer(

  • react中常见hook的使用方式

    1.什么是hook? react hook是react 16.8推出的方法,能够让函数式组件像类式组件一样拥有state.ref.生命周期等属性. 2.为什么要出现hook? 函数式组件是全局当中一个普通函数,在非严格模式下this指向window,但是react内部开启了严格模式,此时this指向undefined,无法像类式组件一样使用state.ref,函数式组件定义的变量都是局部的,当组件进行更新时会重新定义,也无法存储,所以在hook出现之前,函数式组件有很大的局限性,通常情况下都会使

  • 详解tensorflow载入数据的三种方式

    Tensorflow数据读取有三种方式: Preloaded data: 预加载数据 Feeding: Python产生数据,再把数据喂给后端. Reading from file: 从文件中直接读取 这三种有读取方式有什么区别呢? 我们首先要知道TensorFlow(TF)是怎么样工作的. TF的核心是用C++写的,这样的好处是运行快,缺点是调用不灵活.而Python恰好相反,所以结合两种语言的优势.涉及计算的核心算子和运行框架是用C++写的,并提供API给Python.Python调用这些A

  • 插件化机制优雅封装你的hook请求使用方式

    目录 引言 useRequest 简介 架构 useRequest 入口处理 Fetch 和 Plugins state 以及 setState 插件化机制的实现 核心方法 —— runAsync 请求前 —— onBefore 进行请求——onRequest 取消请求 —— onCancel 最后结果处理——onSuccess/onError/onFinally 思考与总结 引言 本文是深入浅出 ahooks 源码系列文章的第二篇,这个系列的目标主要有以下几点: 加深对 React hooks

  • 初探TensorFLow从文件读取图片的四种方式

    本文记录一下TensorFLow的几种图片读取方法,官方文档有较为全面的介绍. 1.使用gfile读图片,decode输出是Tensor,eval后是ndarray import matplotlib.pyplot as plt import tensorflow as tf import numpy as np print(tf.__version__) image_raw = tf.gfile.FastGFile('test/a.jpg','rb').read() #bytes img =

随机推荐