zoukankan      html  css  js  c++  java
  • argparse 在深度学习中的应用

    argparse 介绍

    argparse模块主要用来为脚本传递命令参数功能,使他们更加灵活。

    代码:

    1  parser = argparse.ArgumentParser()   #建立解析器,必须写

    parser.add_argument()

    调用add_argument()向ArgumentParser对象添加命令行参数信息,这些信息告诉ArgumentParser对象如何处理命令行参数。可以通过调用parse_agrs()来使用这些命令行参数。

    参数:

    name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest] 

    name or flags:是必须的参数,该参数接受选项参数或者是位置参数(一串文件名)
    default: 当参数需要默认值时,由这个参数指定,

    type: 使用这个参数,转换输入参数的具体类型,这个参数可以关联到某个自定义的处理函数,这种函数通常用来检查值的范围,以及合法性

    choices: 这个参数用来检查输入参数的范围

    required: 当某个选项指定需要在命令中出现的时候用这个参数

    help: 使用这个参数描述选项作用

    1 parser = argparse.ArgumentParser()
    2 parser.add_argument('--gan_type', type=str, default='GAN',
    3                         choices=['GAN', 'CGAN', 'infoGAN', 'ACGAN', 'EBGAN', 'BEGAN', 'WGAN', 'WGAN_GP', 'DRAGAN', 'LSGAN', 'VAE', 'CVAE'],
    4                         help='The type of GAN', required=True)
    5 parser.add_argument('--dataset', type=str, default='mnist', choices=['mnist', 'fashion-mnist', 'celebA'],
    6                     help='The name of dataset')
    7 parser.add_argument('--epoch', type=int, default=20, help='The number of epochs to run')
    8 parser.add_argument('--batch_size', type=int, default=64, help='The size of batch')
    9 parser.add_argument('--z_dim', type=int, default=62, help='Dimension of noise vector')

    parser.parse_args()

    通过调用parse_args()来解析ArgumentParser对象中保存的命令行参数:将命令行参数解析成相应的数据类型并采取相应的动作,它返回一个Namespace对象。

    1 print(parser.parse_args())

    输出: usage: test.py [-h] --gan_type
    {GAN,CGAN,infoGAN,ACGAN,EBGAN,BEGAN,WGAN,WGAN_GP,DRAGAN,LSGAN,VAE,CVAE}
    [--dataset {mnist,fashion-mnist,celebA}] [--epoch EPOCH]
    [--batch_size BATCH_SIZE] [--z_dim Z_DIM]
    test.py: error: the following arguments are required: --gan_type  因为 required

    这样写的话:

    1 print(parser.parse_args(["--gan_type", "GAN"]))   #传入参数

    输出: Namespace(batch_size=64, dataset='mnist', epoch=20, gan_type='GAN', z_dim=62)

    从对象中直接拿参数:

    
    
    a = parser.parse_args(["--gan_type", "GAN"]
    print(a.z_dim, a.batch_size)

    结果:62 64
  • 相关阅读:
    hdu-5492 Find a path(dp)
    hdu-5493 Queue(二分+树状数组)
    bzoj-2243 2243: [SDOI2011]染色(树链剖分)
    codeforces 724
    codeforces 422A A. Borya and Hanabi(暴力)
    codeforces 442C C. Artem and Array(贪心)
    codeforces 442B B. Andrey and Problem(贪心)
    hdu-5918 Sequence I(kmp)
    poj-3739. Special Squares(二维前缀和)
    hdu-5927 Auxiliary Set(树形dp)
  • 原文地址:https://www.cnblogs.com/WSX1994/p/10914679.html
Copyright © 2011-2022 走看看