tf.contrib.slim add_arg_scope

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

with slim.arg_scope(
      [slim.conv2d, slim.separable_conv2d],
      weights_initializer=tf.truncated_normal_initializer(
          stddev=weights_initializer_stddev),
      activation_fn=activation_fn,
      normalizer_fn=slim.batch_norm if use_batch_norm else None):
    with slim.arg_scope([slim.batch_norm], **batch_norm_params):
    slim.conv2d(
                features,
                num_classes,
                kernel_size=kernel_size,
                rate=rate,
                activation_fn=None,
                normalizer_fn=None,
                scope=scope))

  原理就是使用add_arg_scope函数装饰op,那么op就能查找栈中字典的参数并使用他们,主要代码和上篇文章很类似。

def func_with_args(*args, **kwargs):
  current_scope = current_arg_scope()
  current_args = kwargs
  key_func = arg_scope_func_key(func)
  if key_func in current_scope:
    current_args = current_scope[key_func].copy()
    current_args.update(kwargs)
  return func(*args, **current_args)

  代码逻辑就是先得到当前字典current_arg_scope,此时为{‘conv2d: kargs, 'separable_2d':kargs, 'batch_norm': batch_norm_params}(这里kargs是我偷懒没把代码中initializer等誊写下来),current_args是代码块中参数,这里是features,num_classes等,key_func是’conv2d‘,循环就是如果在字典中有与之相关的参数,则把参数用到函数中。

结语

  写的好像有些简单,下次有灵感再好好改一下。      最后编辑于11:44:51 2018-07-30

猜你喜欢

转载自www.cnblogs.com/zzy-tf/p/9389792.html