python深度學(xué)習(xí)標準庫使用argparse調(diào)參
前言
argparse是深度學(xué)習(xí)項目調(diào)參時常用的python標準庫,使用argparse后,我們在命令行輸入的參數(shù)就可以以這種形式python filename.py --lr 1e-4 --batch_size 32來完成對常見超參數(shù)的設(shè)置。,一般使用時可以歸納為以下三個步驟
使用步驟:
- 創(chuàng)建ArgumentParser()對象
- 調(diào)用add_argument()方法添加參數(shù)
- 使用parse_args()解析參數(shù) 在接下來的內(nèi)容中,我們將以實際操作來學(xué)習(xí)argparse的使用方法
import argparse parser = argparse.ArgumentParser() # 創(chuàng)建一個解析對象 parser.add_argument() # 向該對象中添加你要關(guān)注的命令行參數(shù)和選項 args = parser.parse_args() # 調(diào)用parse_args()方法進行解析
常見規(guī)則
- 在命令行中輸入python demo.py -h或者python demo.py --help可以查看該python文件參數(shù)說明
- arg字典類似python字典,比如arg字典Namespace(integers='5')可使用arg.參數(shù)名來提取這個參數(shù)
- parser.add_argument('integers', type=str, nargs='+',help='傳入的數(shù)字') nargs是用來說明傳入的參數(shù)個數(shù),'+' 表示傳入至少一個參數(shù),'*' 表示參數(shù)可設(shè)置零個或多個,'?' 表示參數(shù)可設(shè)置零個或一個
- parser.add_argument('-n', '--name', type=str, required=True, default='', help='名') required=True表示必須參數(shù), -n表示可以使用短選項使用該參數(shù)
- parser.add_argument("--test_action", default='False', action='store_true')store_true 觸發(fā)時為真,不觸發(fā)則為假(test.py,輸出為 False ,test.py --test_action,輸出為 True)
使用config文件傳入超參數(shù)
為了使代碼更加簡潔和模塊化,可以將有關(guān)超參數(shù)的操作寫在config.py,然后在train.py或者其他文件導(dǎo)入就可以。具體的config.py可以參考如下內(nèi)容。
import argparse def get_options(parser=argparse.ArgumentParser()): parser.add_argument('--workers', type=int, default=0, help='number of data loading workers, you had better put it ' '4 times of your gpu') parser.add_argument('--batch_size', type=int, default=4, help='input batch size, default=64') parser.add_argument('--niter', type=int, default=10, help='number of epochs to train for, default=10') parser.add_argument('--lr', type=float, default=3e-5, help='select the learning rate, default=1e-3') parser.add_argument('--seed', type=int, default=118, help="random seed") parser.add_argument('--cuda', action='store_true', default=True, help='enables cuda') parser.add_argument('--checkpoint_path',type=str,default='', help='Path to load a previous trained model if not empty (default empty)') parser.add_argument('--output',action='store_true',default=True,help="shows output") opt = parser.parse_args() if opt.output: print(f'num_workers: {opt.workers}') print(f'batch_size: {opt.batch_size}') print(f'epochs (niters) : {opt.niter}') print(f'learning rate : {opt.lr}') print(f'manual_seed: {opt.seed}') print(f'cuda enable: {opt.cuda}') print(f'checkpoint_path: {opt.checkpoint_path}') return opt if __name__ == '__main__': opt = get_options()
$ python config.py num_workers: 0 batch_size: 4 epochs (niters) : 10 learning rate : 3e-05 manual_seed: 118 cuda enable: True checkpoint_path:
隨后在train.py等其他文件,我們就可以使用下面的這樣的結(jié)構(gòu)來調(diào)用參數(shù)。
# 導(dǎo)入必要庫 ... import config opt = config.get_options() manual_seed = opt.seed num_workers = opt.workers batch_size = opt.batch_size lr = opt.lr niters = opt.niters checkpoint_path = opt.checkpoint_path # 隨機數(shù)的設(shè)置,保證復(fù)現(xiàn)結(jié)果 def set_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) random.seed(seed) np.random.seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True ... if __name__ == '__main__': set_seed(manual_seed) for epoch in range(niters): train(model,lr,batch_size,num_workers,checkpoint_path) val(model,lr,batch_size,num_workers,checkpoint_path)
argparse中action的可選參數(shù)store_true
# test.py import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--test_action", action='store_true') args = parser.parse_args() action_val = args.test_action print(action_val)
以上面的代碼為例,若觸發(fā) test_action,則為 True, 否則為 False:
- $ python test.py,輸出為 False
- $ python test.py --test_action,輸出為 True
若在上面的代碼中加入default,設(shè)為 False 時:
parser.add_argument("--test_action", default='False', action='store_true')
- $ python test.py,輸出為 False
- $ python test.py --test_action,輸出為 True
default 設(shè)為 True 時:
parser.add_argument("--test_action", default='True', action='store_true')
- $ python test.py,輸出為 True
- $ python test.py --test_action,輸出為 True
參考:http://www.dbjr.com.cn/article/250215.htm
以上就是python深度學(xué)習(xí)標準庫使用argparse調(diào)參的詳細內(nèi)容,更多關(guān)于python標準庫argparse調(diào)參的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python 產(chǎn)生token及token驗證的方法
今天小編就為大家分享一篇python 產(chǎn)生token及token驗證的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12Keras 實現(xiàn)加載預(yù)訓(xùn)練模型并凍結(jié)網(wǎng)絡(luò)的層
這篇文章主要介紹了Keras 實現(xiàn)加載預(yù)訓(xùn)練模型并凍結(jié)網(wǎng)絡(luò)的層,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06