python模块学习-argparse和yacs

提示:最近学习中用到了python,oop的编程思路还不太适应。用到了两个模块,为此记录下笔记。


前言

用到了两个模块一个为argparse,另一个为yacs。
argparse 模块的用处是可以自己编写命令,定义自己需要的一些参数,只需要很简单的几句语句。一般在你自己的项目文件中用上了 argparse 模块之后,在命令行中利用,我认为这种方式在windows中的作用不大(界面友好,点运行就能跑,修改源码中的参数简单),但是在linux中这种在命令行中应用的方式就很便利了
yacs 库就是配置参数的作用。


一、argparse模块

argparse模块

1.1应用方法

argparse 模块可以让人轻松编写用户友好的命令行接口。程序定义它需要的参数,然后 argparse 将弄清如何从 sys.argv 解析出那些参数。 argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。

分成三个步骤:


1.创建一个解析器
使用 argparse 的第一步是创建一个 ArgumentParser 对象:

parser = argparse.ArgumentParser(description='Process some integers.')

ArgumentParser 对象包含将命令行解析成 Python 数据类型所需的全部信息。


2.添加参数
给一个 ArgumentParser 添加程序参数信息是通过调用 add_argument() 方法完成的。通常,这些调用指定 ArgumentParser 如何获取命令行字符串并将其转换为对象。这些信息在 parse_args() 调用时被存储和使用。例如:

parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

然后,调用 parse_args() 将返回一个具有 integers 和 accumulate 两个属性的对象。integers 属性将是一个包含一个或多个整数的列表,而 accumulate 属性当命令行中指定了 --sum 参数时将是 sum() 函数,否则则是 max() 函数。


3.解析参数
ArgumentParser 通过 parse_args() 方法解析参数。它将检查命令行,把每个参数转换为适当的类型然后调用相应的操作。在大多数情况下,这意味着一个简单的 Namespace 对象将从命令行解析出的属性构建:

parser.parse_args(['--sum', '7', '-1', '42'])

在脚本中,通常 parse_args() 会被不带参数调用,而 ArgumentParser 将自动从 sys.argv 中确定命令行参数。


1.2例子

以下代码是一个 Python 程序,它获取一个整数列表并计算总和或者最大值:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

假设上面的 Python 代码保存在名为 prog.py 的文件中,它可以在命令行(windows系统中,在cmd中转到该文件的目录中,prog.py -h即可)运行并提供有用的帮助信息:

$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
 N           an integer for the accumulator

options:
 -h, --help  show this help message and exit
 --sum       sum the integers (default: find the max)

当使用适当的参数运行时,它会输出命令行传入整数的总和或者最大值:

$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4 --sum
10

如果传入无效参数,则会报出错误:

$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'

二、yacs库

yacs库
YACS 被创建为一个轻量级库来定义和管理系统配置,例如在为科学实验而设计的软件中常见的配置。这些“配置”通常涵盖用于训练机器学习模型的超参数或可配置模型超参数等概念,例如卷积神经网络的深度。当做实验时,其可重复性至关重要,因此需要一种可靠的方法来序列化实验配置。YACS 使用 YAML 作为一种简单的、人类可读的序列化格式。范式是:your code + a YACS config for experiment E (+ external dependencies + hardware + other nuisance terms ...) = reproducible experiment E。虽然您可能无法控制所有内容,但至少您可以控制代码和实验性配置。

1.引入库

要在项目中使用 YACS,请首先创建一个项目配置文件,通常称为config.py defaults.py。此文件是所有可配置选项的一站式参考点。它应该有很好的文档记录,并为所有选项提供合理的默认值。

# my_project/config.py
from yacs.config import CfgNode as CN

_C = CN()

_C.SYSTEM = CN()
# Number of GPUS to use in the experiment
_C.SYSTEM.NUM_GPUS = 8
# Number of workers for doing things
_C.SYSTEM.NUM_WORKERS = 4

_C.TRAIN = CN()
# A very important hyperparameter
_C.TRAIN.HYPERPARAMETER_1 = 0.1
# The all important scales for the stuff
_C.TRAIN.SCALES = (2, 4, 8, 16)

def get_cfg_defaults():
  """Get a yacs CfgNode object with default values for my_project."""
  # Return a clone so that the defaults will not be altered
  # This is for the "local variable" use pattern
  return _C.clone()

# Alternatively, provide a way to import the defaults as
# a global singleton:
# cfg = _C  # users can `from config import cfg`

接下来,您将创建 YAML 配置文件;通常,您将为每个实验制作一个。每个配置文件仅覆盖该实验中更改的选项。

# my_project/experiment.yaml
SYSTEM:
  NUM_GPUS: 2
TRAIN:
  SCALES: (1, 2)

最后,您将获得使用配置系统的实际项目代码。在任何初始设置之后,最好通过freeze()调用该方法将其冻结以防止进一步修改。如下图所示,配置选项可以通过直接导入cfg和访问来使用一组全局选项,也可以复制并作为参数传递。

# my_project/main.py

import my_project
from config import get_cfg_defaults  # local variable usage pattern, or:
# from config import cfg  # global singleton usage pattern


if __name__ == "__main__":
  cfg = get_cfg_defaults()
  cfg.merge_from_file("experiment.yaml")
  cfg.freeze()
  print(cfg)

  # Example of using the cfg as global access to options
  if cfg.SYSTEM.NUM_GPUS > 0:
    my_project.setup_multi_gpu_support()

  model = my_project.create_model(cfg)

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

请叫我7plus

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值