python深度學(xué)習(xí)標(biāo)準(zhǔn)庫(kù)使用argparse調(diào)參
前言
argparse是深度學(xué)習(xí)項(xiàng)目調(diào)參時(shí)常用的python標(biāo)準(zhǔn)庫(kù),使用argparse后,我們?cè)诿钚休斎氲膮?shù)就可以以這種形式python filename.py --lr 1e-4 --batch_size 32來完成對(duì)常見超參數(shù)的設(shè)置。,一般使用時(shí)可以歸納為以下三個(gè)步驟
使用步驟:
- 創(chuàng)建ArgumentParser()對(duì)象
- 調(diào)用add_argument()方法添加參數(shù)
- 使用parse_args()解析參數(shù) 在接下來的內(nèi)容中,我們將以實(shí)際操作來學(xué)習(xí)argparse的使用方法
import argparse parser = argparse.ArgumentParser() # 創(chuàng)建一個(gè)解析對(duì)象 parser.add_argument() # 向該對(duì)象中添加你要關(guān)注的命令行參數(shù)和選項(xiàng) args = parser.parse_args() # 調(diào)用parse_args()方法進(jìn)行解析
常見規(guī)則
- 在命令行中輸入python demo.py -h或者python demo.py --help可以查看該python文件參數(shù)說明
- arg字典類似python字典,比如arg字典Namespace(integers='5')可使用arg.參數(shù)名來提取這個(gè)參數(shù)
- parser.add_argument('integers', type=str, nargs='+',help='傳入的數(shù)字') nargs是用來說明傳入的參數(shù)個(gè)數(shù),'+' 表示傳入至少一個(gè)參數(shù),'*' 表示參數(shù)可設(shè)置零個(gè)或多個(gè),'?' 表示參數(shù)可設(shè)置零個(gè)或一個(gè)
- parser.add_argument('-n', '--name', type=str, required=True, default='', help='名') required=True表示必須參數(shù), -n表示可以使用短選項(xiàng)使用該參數(shù)
- parser.add_argument("--test_action", default='False', action='store_true')store_true 觸發(fā)時(shí)為真,不觸發(fā)則為假(test.py,輸出為 False ,test.py --test_action,輸出為 True)
使用config文件傳入超參數(shù)
為了使代碼更加簡(jiǎn)潔和模塊化,可以將有關(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)入必要庫(kù)
...
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
# 隨機(jī)數(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 時(shí):
parser.add_argument("--test_action", default='False', action='store_true')- $ python test.py,輸出為 False
- $ python test.py --test_action,輸出為 True
default 設(shè)為 True 時(shí):
parser.add_argument("--test_action", default='True', action='store_true')
- $ python test.py,輸出為 True
- $ python test.py --test_action,輸出為 True
參考:http://www.dhdzp.com/article/250215.htm
以上就是python深度學(xué)習(xí)標(biāo)準(zhǔn)庫(kù)使用argparse調(diào)參的詳細(xì)內(nèi)容,更多關(guān)于python標(biāo)準(zhǔn)庫(kù)argparse調(diào)參的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python 創(chuàng)建空的list,以及append用法講解
今天小編就為大家分享一篇Python 創(chuàng)建空的list,以及append用法講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05
python基礎(chǔ)教程之基本內(nèi)置數(shù)據(jù)類型介紹
在Python程序中,每個(gè)數(shù)據(jù)都是對(duì)像,每個(gè)對(duì)像都有自己的一個(gè)類型。不同類型有不同的操作方法,使用內(nèi)置數(shù)據(jù)類型獨(dú)有的操作方法,可以更快的完成很多工作2014-02-02
對(duì)python requests發(fā)送json格式數(shù)據(jù)的實(shí)例詳解
今天小編就為大家分享一篇對(duì)python requests發(fā)送json格式數(shù)據(jù)的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12
Python爬蟲基礎(chǔ)之XPath語法與lxml庫(kù)的用法詳解
這篇文章主要給大家介紹了關(guān)于Python爬蟲基礎(chǔ)之XPath語法與lxml庫(kù)用法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09

