argparse是深度学习项目调参时常用的python标准库,使用argparse后,我们在命令行输入的参数就可以以这种形式python filename.py --lr 1e-4 --batch_size 32来完成对常见超参数的设置。,一般使用时可以归纳为以下三个步骤

使用步骤:

  • 创建ArgumentParser()对象
  • 调用add_argument()方法添加参数
  • 使用parse_args()解析参数 在接下来的内容中,我们将以实际操作来学习argparse的使用方法
import argparse

parser = argparse.ArgumentParser() # 创建一个解析对象

parser.add_argument() # 向该对象中添加你要关注的命令行参数和选项

args = parser.parse_args() # 调用parse_args()方法进行解析

常见规则

  • 在命令行中输入python demo.py -h或者python demo.py --help可以查看该python文件参数说明
  • arg字典类似python字典,比如arg字典Namespace(integers='5')可使用arg.参数名来提取这个参数
  • parser.add_argument('integers', type=str, nargs='+',help='传入的数字') nargs是用来说明传入的参数个数,'+' 表示传入至少一个参数,'*' 表示参数可设置零个或多个,'?' 表示参数可设置零个或一个
  • parser.add_argument('-n', '--name', type=str, required=True, default='', help='名') required=True表示必须参数, -n表示可以使用短选项使用该参数
  • parser.add_argument("--test_action", default='False', action='store_true')store_true 触发时为真,不触发则为假(test.py,输出为 Falsetest.py --test_action,输出为 True

使用config文件传入超参数

为了使代码更加简洁和模块化,可以将有关超参数的操作写在config.py,然后在train.py或者其他文件导入就可以。具体的config.py可以参考如下内容。

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等其他文件,我们就可以使用下面的这样的结构来调用参数。

# 导入必要库
...
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 # 随机数的设置,保证复现结果
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)

参考:

https://zhuanlan.zhihu.com/p/56922793

(14条消息) python argparse中action的可选参数store_true的作用_元气少女wuqh的博客-CSDN博客

[6.6 使用argparse进行调参 — 深入浅出PyTorch (datawhalechina.github.io)](https://datawhalechina.github.io/thorough-pytorch/第六章/6.6 使用argparse进行调参.html)

使用argparse进行调参的更多相关文章

  1. scikit-learn随机森林调参小结

    在Bagging与随机森林算法原理小结中,我们对随机森林(Random Forest, 以下简称RF)的原理做了总结.本文就从实践的角度对RF做一个总结.重点讲述scikit-learn中RF的调参注 ...

  2. scikit-learn 梯度提升树(GBDT)调参小结

    在梯度提升树(GBDT)原理小结中,我们对GBDT的原理做了总结,本文我们就从scikit-learn里GBDT的类库使用方法作一个总结,主要会关注调参中的一些要点. 1. scikit-learn ...

  3. word2vec参数调整 及lda调参

     一.word2vec调参   ./word2vec -train resultbig.txt -output vectors.bin -cbow 0 -size 200 -window 5 -neg ...

  4. scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类 (python代码)

    scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类数据集 fetch_20newsgroups #-*- coding: UTF-8 -*- import ...

  5. 基于pytorch的CNN、LSTM神经网络模型调参小结

    (Demo) 这是最近两个月来的一个小总结,实现的demo已经上传github,里面包含了CNN.LSTM.BiLSTM.GRU以及CNN与LSTM.BiLSTM的结合还有多层多通道CNN.LSTM. ...

  6. 漫谈PID——实现与调参

    闲话: 作为一个控制专业的学生,说起PID,真是让我又爱又恨.甚至有时候会觉得我可能这辈子都学不会pid了,但是经过一段时间的反复琢磨,pid也不是很复杂.所以在看懂pid的基础上,写下这篇文章,方便 ...

  7. hyperopt自动调参

    hyperopt自动调参 在传统机器学习和深度学习领域经常需要调参,调参有些是通过通过对数据和算法的理解进行的,这当然是上上策,但还有相当一部分属于"黑盒" hyperopt可以帮 ...

  8. 调参必备---GridSearch网格搜索

    什么是Grid Search 网格搜索? Grid Search:一种调参手段:穷举搜索:在所有候选的参数选择中,通过循环遍历,尝试每一种可能性,表现最好的参数就是最终的结果.其原理就像是在数组里找最 ...

  9. random froest 调参

    https://blog.csdn.net/wf592523813/article/details/86382037 https://blog.csdn.net/xiayto/article/deta ...

随机推荐

  1. Canvas 制作海报

      HTML <template> <view class="content"> <view class="flex_row_c_c mod ...

  2. mosquitto使用与常用配置

    为了方便演示,我这里就用windows环境下安装的mosquitto进行操作,操作方式和linux系统下是一样的. 一.windows安装mosquitto 下载mosquitto mosquitto ...

  3. 自家APP打开微信小程序,可行吗?

    小程序的通用解决方案,今天为大家介绍一下FinClip.它的最大特点,就是能够让任何 App 运行小程序. 只需要在你的 App 里面,引入它的 SDK,就能加载运行外部小程序了.除了 SDK,它还提 ...

  4. 线程的概念及Thread模块的使用

    线程 一.什么是线程? 我们可以把进程理解成一个资源空间,真正被CPU执行的就是进程里的线程. 一个进程中最少会有一条线程,同一进程下的每个线程之间资源是共享的. 二.开设线程的两种方式 开设进程需要 ...

  5. 【2021 ICPC Asia Jinan 区域赛】 C Optimal Strategy推公式-组合数-逆元快速幂

    题目链接 题目详情 (pintia.cn) 题目 题意 有n个物品在他们面前,编号从1自n.两人轮流移走物品.在移动中,玩家选择未被拿走的物品并将其拿走.当所有物品被拿走时,游戏就结束了.任何一个玩家 ...

  6. 初学Java时没有理解的一些概念

    背景 之前学Java属于赶鸭子上架,草草学习基础语法便直接做课程作业,许多概念问题仍不清楚,故在此梳理一下,主要参考廖雪峰和互联网资料. Java运行方式与JVM Java是介于编译型语言(C++)和 ...

  7. Spring从入门到源码—IOC基本使用(二)

    1.spring_helloworld 使用maven的方式来构建项目(Mavaen) 添加对应的pom依赖 pom.xml <dependencies> <!-- https:// ...

  8. linux在图形界面一登录就自动闪退

    今天一登录linux图形界面就自动退出了,又退到了登录界面了,密码是正确的. 解决方法如下: 1. 先按 Ctrl + Alt + F1,进入 命令行模式. 2. 在命令行里,输入用户名密码正常登录. ...

  9. [AcWing 36] 合并两个排序的链表

    点击查看代码 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * L ...

  10. dfs深搜

    一.01背包dfs //回溯法,01背包 #include<iostream> #include<algorithm> using namespace std; const i ...