slim.arg_scope函数说明如下:
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 or
a dictionary containing the current scope. When list_ops_or_scope is a
dict, 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 in
list_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.
因此使用@slim.add_arg_scope修饰目标函数,从而达到用slim.arg_scope为目标函数设置默认参数的目的。而库中的conv2d等函数,已经被默认声明。因此,可以在构建网络时,快捷设置,达到节省时间的目的。同时,也可以通过下面的方式进行单独设置。
with slim.arg_scope(
[slim.conv2d,slim.max_pool2d],stride = 1,padding = 'SAME'):
net = slim.conv2d(net,32,[3,3],stride=2,scope = 'conv1')
装饰器@
# 装饰器
import time
# 装饰器,记录函数运行时间
def decorator01(fun):
def wapper():
stime = time.time()#'装饰'
fun()#第三步:执行函数功能
etime = time.time()#’装饰‘
print("fun run time is {TIME}".format(TIME=etime - stime))
return wapper # 必须要返回一个函数的内存地址
#第一步运行到这里的时候, 使用装饰器装饰某个函数,这里等价于 test01=decorator01(test01),(所谓装饰之意?)
# 即将test01实际引用变成wapper函数内存地址,所以执行test01实际是执行wapper
@decorator01
def test01():
time.sleep(2)
print("test01 is running")
#第二步:这里的时候就执行wapper()了,
test01() # 不修改代码和调用方式,实现添加记录时间功能
带参数的装饰器
# 装饰器
import time
# 如果装饰器有参数,最外层是装饰器的参数
def decorator01(*args, **kwargs):
print("装饰器参数:", *args, **kwargs)
def out(fun): #第二层才是接受的函数
def wapper(*args, **kwargs): # 使用非固定参数,无论参数是什么,都可以传递进来
stime = time.time()
fun(*args, **kwargs)
etime = time.time()
print("fun run time is {TIME}".format(TIME=etime - stime))
return wapper # 必须要返回一个函数的内存地址
return out # 要返回装饰函数的内存地址
#第一步: 装饰器本身带参数,此时 decorator01(arg)=out,即相当于 @out装饰test01,所以 test01=out(fun)=wapper
@decorator01(1)
def test01(args1):
time.sleep(2)
print("参数是 {NAME} ".format(NAME=args1))
test01("侯征") # 不修改代码和调用方式,实现添加记录时间功能