【https://blog.csdn.net/u013921430 转载】

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


  1. @tf_contextlib.contextmanager
  2. def arg_scope(list_ops_or_scope, **kwargs):
  3. """Stores the default arguments for the given set of list_ops.
  4. For usage, please see examples at top of the file.
  5. Args:
  6. list_ops_or_scope: List or tuple of operations to set argument scope for or
  7. a dictionary containing the current scope. When list_ops_or_scope is a
  8. dict, kwargs must be empty. When list_ops_or_scope is a list or tuple,
  9. then every op in it need to be decorated with @add_arg_scope to work.
  10. **kwargs: keyword=value that will define the defaults for each op in
  11. list_ops. All the ops need to accept the given set of arguments.
  12. Yields:
  13. the current_scope, which is a dictionary of {op: {arg: value}}
  14. Raises:
  15. TypeError: if list_ops is not a list or a tuple.
  16. ValueError: if any op in list_ops has not be decorated with @add_arg_scope.
  17. """
  18. if isinstance(list_ops_or_scope, dict):
  19. # Assumes that list_ops_or_scope is a scope that is being reused.
  20. if kwargs:
  21. raise ValueError('When attempting to re-use a scope by suppling a'
  22. 'dictionary, kwargs must be empty.')
  23. current_scope = list_ops_or_scope.copy()
  24. try:
  25. _get_arg_stack().append(current_scope)
  26. yield current_scope
  27. finally:
  28. _get_arg_stack().pop()
  29. else:
  30. # Assumes that list_ops_or_scope is a list/tuple of ops with kwargs.
  31. if not isinstance(list_ops_or_scope, (list, tuple)):
  32. raise TypeError('list_ops_or_scope must either be a list/tuple or reused'
  33. 'scope (i.e. dict)')
  34. try:
  35. current_scope = current_arg_scope().copy()
  36. for op in list_ops_or_scope:
  37. key_op = _key_op(op)
  38. if not has_arg_scope(op):
  39. raise ValueError('%s is not decorated with @add_arg_scope',
  40. _name_op(op))
  41. if key_op in current_scope:
  42. current_kwargs = current_scope[key_op].copy()
  43. current_kwargs.update(kwargs)
  44. current_scope[key_op] = current_kwargs
  45. else:
  46. current_scope[key_op] = kwargs.copy()
  47. _get_arg_stack().append(current_scope)
  48. yield current_scope
  49. finally:
  50. _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()为它设置默认参数。


  1. import tensorflow as tf
  2. slim =tf.contrib.slim
  3. @slim.add_arg_scope
  4. def fun1(a=0,b=0):
  5. return (a+b)
  6. with slim.arg_scope([fun1],a=10):
  7. x=fun1(b=30)
  8. print(x)

运行结果为:

40

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


  1. @add_arg_scope
  2. def convolution(inputs,
  3. num_outputs,
  4. kernel_size,
  5. stride=1,
  6. padding='SAME',
  7. data_format=None,
  8. rate=1,
  9. activation_fn=nn.relu,
  10. normalizer_fn=None,
  11. normalizer_params=None,
  12. weights_initializer=initializers.xavier_initializer(),
  13. weights_regularizer=None,
  14. biases_initializer=init_ops.zeros_initializer(),
  15. biases_regularizer=None,
  16. reuse=None,
  17. variables_collections=None,
  18. outputs_collections=None,
  19. trainable=True,
  20. scope=None):

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


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

@修饰符

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


  1. @fun_a #等价于fun_a(fun_b)
  2. def fun_b():

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


  1. def funs(fun,factor=20):
  2. x=fun()
  3. print(factor*x)
  4. @funs #等价funs(add(),fator=20)
  5. def add(a=10,b=20):
  6. return(a+b)

slim.arg_scope()的使用的更多相关文章

  1. slim.arg_scope中python技巧

    slim.arg_scope函数说明如下: Stores the default arguments for the given set of list_ops. For usage, please ...

  2. tf.contrib.slim arg_scope

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

  3. 使用多块GPU进行训练 1.slim.arg_scope(对于同等类型使用相同操作) 2.tf.name_scope(定义名字的范围) 3.tf.get_variable_scope().reuse_variable(参数的复用) 4.tf.py_func(构造函数)

    1. slim.arg_scope(函数, 传参) # 对于同类的函数操作,都传入相同的参数 from tensorflow.contrib import slim as slim import te ...

  4. 【Tensorflow】slim.arg_scope()的使用

    https://blog.csdn.net/u013921430/article/details/80915696

  5. TensorFlow和最近发布的slim

    笔者将和大家分享一个结合了TensorFlow和最近发布的slim库的小应用,来实现图像分类.图像标注以及图像分割的任务,围绕着slim展开,包括其理论知识和应用场景. 之前自己尝试过许多其它的库,比 ...

  6. 用tensorlayer导入Slim模型迁移学习

    上一篇博客[用tensorflow迁移学习猫狗分类]笔者讲到用tensorlayer的[VGG16模型]迁移学习图像分类,那麽问题来了,tensorlayer没提供的模型怎么办呢?别担心,tensor ...

  7. tf.contrib.slim add_arg_scope

    上一篇文章中我们介绍了arg_scope函数,它在每一层嵌套中update当前字典中参数形成新的字典,并入栈.那么这些参数是怎么作用到代码块中的函数的呢?比如说如下情况: with slim.arg_ ...

  8. 第二十四节,TensorFlow下slim库函数的使用以及使用VGG网络进行预训练、迁移学习(附代码)

    在介绍这一节之前,需要你对slim模型库有一些基本了解,具体可以参考第二十二节,TensorFlow中的图片分类模型库slim的使用.数据集处理,这一节我们会详细介绍slim模型库下面的一些函数的使用 ...

  9. 第二十二节,TensorFlow中的图片分类模型库slim的使用、数据集处理

    Google在TensorFlow1.0,之后推出了一个叫slim的库,TF-slim是TensorFlow的一个新的轻量级的高级API接口.这个模块是在16年新推出的,其主要目的是来做所谓的“代码瘦 ...

随机推荐

  1. 深入学习Redis持久化

    一.Redis高可用概述 在介绍Redis高可用之前,先说明一下在Redis的语境中高可用的含义. 我们知道,在web服务器中,高可用是指服务器可以正常访问的时间,衡量的标准是在多长时间内可以提供正常 ...

  2. Ubuntu中实现Docker内安装jenkins+jenkins远程触发

    前面做了在ubuntu中安装jenkins+docker实现自动部署,但是得安装jdk8+tomcat8环境,比较麻烦,因此本文记录如何将jenkins直接装在dockers内并且实现远程触发功能. ...

  3. 浅谈maven自动化构建工具

    转载https://blog.csdn.net/zxm1306192988/article/details/76209062 Maven是什么[what] 1.Maven 是 Apache 软件基金会 ...

  4. Win10桌面图标显示不正常变成了白色

    开机不知道什么原因,windows 10 桌面图标全部变成了白色,软件是可以点击正常打开使用,但是看着特别不爽.今天就告诉大家一种办法,解决这种问题. 解决步骤 1.在桌面右键新建 "文本文 ...

  5. Python中的try-finally

    >>> try: ... raise KeyboardInterrupt ... finally: ... print('Goodbye, world!') ... Goodbye, ...

  6. yum工具入门

    一yum介绍 注意学完了yum之后,rpm的使用频率就少了.有些功能yum用起来不如rpm更方便. CentOS: yum, dnfYUM: Yellowdog Update Modifier,rpm ...

  7. 双11大考 POLARDB分钟级弹性让企业轻松扩展

    无处不在的脉冲计算 阿里有双11,中国有春运,高考后有分数出来的那天,歌迷心中有周杰伦演唱会门票在线开售之时....有人的地方就有江湖,有人的地方也有脉冲计算,这些热点事件背后都需要大量的计算资源给予 ...

  8. jsp标签的介绍

    cankao:http://www.cnblogs.com/xdp-gacl/p/3788369.html jsp常用的标签有以下3个 1.<jsp:include>标签 2.<js ...

  9. 使用html5进行视频播放

    一直以来网页大多是使用 flash 来播放视频.在目前唱衰 flash 的环境下,HTML5 为我们带来了一个网页内视频播放的解决方案—— <video>标签. 在HTML5 中,可以通过 ...

  10. Redis缓存接入监控、运维平台CacheCloud

    改造RedisConnectionFactory /** * 根据缓存策略的不同,RedisConnectionFactory不同 * 示例是单机模式. * * @return */@Beanpubl ...