【fishing-pan:https://blog.csdn.net/u013921430 转载请注明出处】


slim.arg_scope() 函数的使用

slim是一种轻量级的tensorflow库,可以使模型的构建,训练,测试都变得更加简单。在slim库中对很多常用的函数进行了定义,slim.arg_scope()是slim库中经常用到的函数之一。函数的定义如下;

@tf_contextlib.contextmanager
def arg_scope(list_ops_or_scope, **kwargs):"""Stores the default arguments for the given set of list_ops.For usage, please see examples at top of the file.Args:list_ops_or_scope: List or tuple of operations to set argument scope for ora dictionary containing the current scope. When list_ops_or_scope is adict, kwargs must be empty. When list_ops_or_scope is a list or tuple,then every op in it need to be decorated with @add_arg_scope to work.**kwargs: keyword=value that will define the defaults for each op inlist_ops. All the ops need to accept the given set of arguments.Yields:the current_scope, which is a dictionary of {op: {arg: value}}Raises:TypeError: if list_ops is not a list or a tuple.ValueError: if any op in list_ops has not be decorated with @add_arg_scope."""if isinstance(list_ops_or_scope, dict):# Assumes that list_ops_or_scope is a scope that is being reused.if kwargs:raise ValueError('When attempting to re-use a scope by suppling a''dictionary, kwargs must be empty.')current_scope = list_ops_or_scope.copy()try:_get_arg_stack().append(current_scope)yield current_scopefinally:_get_arg_stack().pop()else:# Assumes that list_ops_or_scope is a list/tuple of ops with kwargs.if not isinstance(list_ops_or_scope, (list, tuple)):raise TypeError('list_ops_or_scope must either be a list/tuple or reused''scope (i.e. dict)')try:current_scope = current_arg_scope().copy()for op in list_ops_or_scope:key_op = _key_op(op)if not has_arg_scope(op):raise ValueError('%s is not decorated with @add_arg_scope',_name_op(op))if key_op in current_scope:current_kwargs = current_scope[key_op].copy()current_kwargs.update(kwargs)current_scope[key_op] = current_kwargselse:current_scope[key_op] = kwargs.copy()_get_arg_stack().append(current_scope)yield current_scopefinally:_get_arg_stack().pop()

如注释中所说,这个函数的作用是给list_ops中的内容设置默认值。但是每个list_ops中的每个成员需要用@add_arg_scope修饰才行。所以使用slim.arg_scope()有两个步骤:

  1. 使用@slim.add_arg_scope修饰目标函数
  2. 用 slim.arg_scope()为目标函数设置默认参数.

例如如下代码;首先用@slim.add_arg_scope修饰目标函数fun1(),然后利用slim.arg_scope()为它设置默认参数。

import tensorflow as tf
slim =tf.contrib.slim@slim.add_arg_scope
def fun1(a=0,b=0):return (a+b)with slim.arg_scope([fun1],a=10):x=fun1(b=30)print(x)

运行结果为:

40

平常所用到的slim.conv2d( ),slim.fully_connected( ),slim.max_pool2d( )等函数在他被定义的时候就已经添加了@add_arg_scope。以slim.conv2d( )为例;

@add_arg_scope
def convolution(inputs,num_outputs,kernel_size,stride=1,padding='SAME',data_format=None,rate=1,activation_fn=nn.relu,normalizer_fn=None,normalizer_params=None,weights_initializer=initializers.xavier_initializer(),weights_regularizer=None,biases_initializer=init_ops.zeros_initializer(),biases_regularizer=None,reuse=None,variables_collections=None,outputs_collections=None,trainable=True,scope=None):

所以,在使用过程中可以直接slim.conv2d( )等函数设置默认参数。例如在下面的代码中,不做单独声明的情况下,slim.conv2d, slim.max_pool2d, slim.avg_pool2d三个函数默认的步长都设为1,padding模式都是'VALID'的。但是也可以在调用时进行单独声明。这种参数设置方式在构建网络模型时,尤其是较深的网络时,可以节省时间。

 with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],stride = 1, padding = 'VALID'):net = slim.conv2d(inputs, 32, [3, 3], stride = 2, scope = 'Conv2d_1a_3x3')net = slim.conv2d(net, 32, [3, 3], scope = 'Conv2d_2a_3x3')net = slim.conv2d(net, 64, [3, 3], padding = 'SAME', scope = 'Conv2d_2b_3x3')

@修饰符

其实这种用法是python中常用到的。在python中@修饰符放在函数定义的上方,它将被修饰的函数作为参数,并返回修饰后的同名函数。形式如下;

@fun_a     #等价于fun_a(fun_b)
def fun_b():

这在本质上讲跟直接调用被修饰的函数没什么区别,但是有时候也有用处,例如在调用被修饰函数前需要输出时间信息,我们可以在@后方的函数中添加输出时间信息的语句,这样每次我们只需要调用@后方的函数即可。

def funs(fun,factor=20):x=fun()print(factor*x)@funs     #等价funs(add(),fator=20)
def add(a=10,b=20):return(a+b)

【Tensorflow】slim.arg_scope()的使用相关推荐

  1. tf.contrib.slim arg_scope

    缘由 最近一直在看深度学习的代码,又一次看到了slim.arg_scope()的嵌套使用,具体代码如下: with slim.arg_scope([slim.conv2d, slim.separabl ...

  2. tensorflow: slim

    最近需要使用slim模块,用到哪里翻译哪里.原文及译文用正体,个人收获用斜体加下划线. slim的github readme:https://github.com/tensorflow/tensorf ...

  3. Tensorflow slim库

    slim这个模块是在16年新推出的,其主要目的是来做所谓的"代码瘦身". github上面大部分tensorflow的工程都会涉及到它,不得不说,撇开Keras,TensorLay ...

  4. slim.arg_scope()的使用

    slim.arg_scope() 函数的使用 slim是一种轻量级的tensorflow库,可以使模型的构建,训练,测试都变得更加简单.在slim库中对很多常用的函数进行了定义,slim.arg_sc ...

  5. TensorFlow Slim 工具包使用

    TensorFlow Slim是Google提供的图像分类工具包,不仅提供一些方便接口,包含使用tf_slim训练和评估几个广泛使用于图像识别的卷积神经网络 (CNN) 图像分类模型的代码 ,还包含允 ...

  6. 打造自己的图像识别模型2——使用 TensorFlow Slim 微调模型

    最近在搞自己的深度学习图像识别模型.这是第二步 本文主要讲解在现有常用模型基础上,如何微调模型,减少训练时间,同时保持模型检测精度. 主要参考书籍<21个项目玩转深度学习:基于TensorFlo ...

  7. tensorflow slim 安装教程

    参考链接: https://www.cnblogs.com/zyly/p/9145081.html https://blog.csdn.net/qq_27882063/article/details/ ...

  8. 【深度学习-微调模型】使用Tensorflow Slim fine-tune(微调)模型

    本文主要讲解在现有常用模型基础上,如何微调模型,减少训练时间,同时保持模型检测精度. 首先介绍下Slim这个Google公布的图像分类工具包,可在github链接:modules and exampl ...

  9. Tensorflow Slim入门教程(1)

    slim入门教程 slim入门教程 1. Variable 2. Layers 2.1 slim.bias_add 2.2 slim.batch_norm 2.3 slim.conv2d 2.4 sl ...

最新文章

  1. 科大讯飞全新1024:3大计划,200项A.I.能力,全链路驱动应用场景创新!
  2. 重要通知:招募200程序员,免费培训金融知识,不限年龄,有意者进!
  3. java bean 工厂模式_Spring框架通过工厂创建Bean的三种方式实现
  4. Wordcounter,使用Lambdas和Fork / Join计算Java中的单词数
  5. 行为设计模式 - 状态设计模式
  6. 扎克伯格5小时听证鏖战:五大焦点,四处尴尬,一次耿直CEO笑翻全场
  7. 贪吃蛇系列之七——有吃的啦
  8. celery配合rabbitmq任务队列实现任务的异步调度执行[celery redis]
  9. Linux中history命令增加时间显示
  10. CSS基础(六)——还原设计稿
  11. jetson-nano编译qt5.15.2带opengl,xcb
  12. 打破少儿编程学习进度中的技术关
  13. 联想拯救者R7000P2021安装Ubuntu双系统
  14. 斐讯路由器宽带运营商服务器,新版斐讯p.to路由器的设置教程
  15. ELF二进制目标文件详解
  16. adobe flash(转载)
  17. MVC 图片上传 带进度条(转)
  18. 计算机毕设(附源码)JAVA-SSM基于web的图书借阅管理系统
  19. STM32——EMWIN窗口小工具(十三)
  20. MATSIM使用教程

热门文章

  1. JavaScript之arguments属性
  2. vue性能优化-------vendor优化详细用法(瘦身),减小体积,引入cdn
  3. ORA-19809: limit exceeded for recovery files问题解决
  4. 服务监控 Spring Boot Actuator 介绍
  5. Mblog 开源Java多人博客系统
  6. C语言,利用一维数组交换法排序,使学生成绩高低排序(要求输入为负值时输入结束)
  7. 投屏时,客厅电视与客厅电视DMR的区别
  8. net core 3.1 swagger文档添加 不用xml配置
  9. 浅谈CC攻击原理与防范
  10. okHttp记录---response.body().string()输出的结构是乱码