slim.arg_scope中python技巧


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("侯征")  # 不修改代碼和調用方式,實現添加記錄時間功能


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM