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.dbjr.com.cn/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?opencv進(jìn)行圓形識(shí)別(圓檢測(cè))實(shí)例代碼
最近工作的項(xiàng)目上需要檢測(cè)圖像中是否有圓形,下面這篇文章主要給大家介紹了關(guān)于Python?opencv進(jìn)行圓形識(shí)別(圓檢測(cè))的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05深入探究Flask的兩個(gè)高級(jí)特性之藍(lán)圖和JWT認(rèn)證
本文將探討 Flask 的兩個(gè)高級(jí)特性:藍(lán)圖(Blueprints)和 JSON Web Token(JWT)認(rèn)證,藍(lán)圖讓我們可以將應(yīng)用模塊化,以便更好地組織代碼;而 JWT 認(rèn)證是現(xiàn)代 Web 應(yīng)用中常見的一種安全機(jī)制,感興趣的小伙伴跟著小編一起來看看吧2023-08-08python 產(chǎn)生token及token驗(yàn)證的方法
今天小編就為大家分享一篇python 產(chǎn)生token及token驗(yàn)證的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12Keras 實(shí)現(xiàn)加載預(yù)訓(xùn)練模型并凍結(jié)網(wǎng)絡(luò)的層
這篇文章主要介紹了Keras 實(shí)現(xiàn)加載預(yù)訓(xùn)練模型并凍結(jié)網(wǎng)絡(luò)的層,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python實(shí)現(xiàn)快速保存微信公眾號(hào)文章中的圖片
這篇文章主要為大家詳細(xì)介紹了如何利用Python語言實(shí)現(xiàn)快速保存微信公眾號(hào)文章中的圖片,文中的示例代碼講解詳細(xì),感興趣的可以嘗試一下2022-06-06