天天看點

Python argparse 子產品介紹argparse

Python argparse 子產品介紹

argparse

argparse 是 Python 内置的一個用于指令項選項與參數解析的子產品,可以友善程式執行的時候傳遞參數,下面将介紹一下具體的用法:

子產品導入

由于是python内置的子產品,直接import即可:

import argparse
           

簡單例子

import argparse
parse = argparse.ArgumentParser()
parse.add_argument("--echo",type=str,required=False,default='alaoshi')
args = parse.parse_args()
print(args)
print(args.echo)
           
運作結果:Namespace(echo='zoujun')
zoujun
           

例子說明

  1. argparse.ArgumentParser(),生成解釋器
  2. parse.add_argument(),為解釋器設定參數
  3. args = parse.parse_args(),解析添加的參數

argparse.ArgumentParser()參數說明

decription-添加描述,不設定預設為None

其他包括(prog,fromfile_prefix_chars,argument_default),由于用的較少,不作介紹

parser=argparse.ArgumentParser(description="A description of what the program does")
           

parse.add_argument()參數說明`

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
           

參數詳解

name or flags -指定傳入的參數的形式,一般寫兩個(-,–)

action -指令行遇到參數時的動作

  1. store_true,表示有傳參時把變量指派true,否則為false;
  2. store_const,參數指派const
  3. append,将遇到的值存儲成清單
  4. count,存儲遇到的次數

nargs -需要傳入的參數個數,“?”表示0個或者一個參數,+ 号表示 1 或多個參數

const - action 和 nargs 所需要的常量值

type - 指令行參數應該被轉換成的類型

required - 若為true,則必須輸入參數,為false則必須設定default(隻對可選參數)

choices - 候選值,輸出參數必須在候選值裡面

default - 不指定參數時的預設值

help - 參數的幫助資訊

dest - 解析後的參數名稱

-h:輸出參數使用說明資訊

具體的例子

def get_arguments():
    """Parse all the arguments provided from the CLI.
    
    Returns:
      A list of parsed arguments.
    """
    parser = argparse.ArgumentParser(description="DeepLab-ResNet Network")
    parser.add_argument("--batch-size", type=int, default=BATCH_SIZE,
                        help="Number of images sent to the network in one step.")
    parser.add_argument("--data-dir", type=str, default=DATA_DIRECTORY,
                        help="Path to the directory containing the PASCAL VOC dataset.")
    parser.add_argument("--data-list", type=str, default=DATA_LIST_PATH,
                        help="Path to the file listing the images in the dataset.")
    parser.add_argument("--ignore-label", type=int, default=IGNORE_LABEL,
                        help="The index of the label to ignore during the training.")
    parser.add_argument("--input-size", type=str, default=INPUT_SIZE,
                        help="Comma-separated string with height and width of images.")
    parser.add_argument("--is-training", action="store_true",
                        help="Whether to updates the running means and variances during the training.")
    parser.add_argument("--learning-rate", type=float, default=LEARNING_RATE,
                        help="Base learning rate for training with polynomial decay.")
    parser.add_argument("--momentum", type=float, default=MOMENTUM,
                        help="Momentum component of the optimiser.")
    parser.add_argument("--not-restore-last", action="store_true",
                        help="Whether to not restore last (FC) layers.")
    parser.add_argument("--num-classes", type=int, default=NUM_CLASSES,
                        help="Number of classes to predict (including background).")
    parser.add_argument("--num-steps", type=int, default=NUM_STEPS,
                        help="Number of training steps.")
    parser.add_argument("--power", type=float, default=POWER,
                        help="Decay parameter to compute the learning rate.")
    parser.add_argument("--random-mirror", action="store_true",
                        help="Whether to randomly mirror the inputs during the training.")
    parser.add_argument("--random-scale", action="store_true",
                        help="Whether to randomly scale the inputs during the training.")
    parser.add_argument("--random-seed", type=int, default=RANDOM_SEED,
                        help="Random seed to have reproducible results.")
    parser.add_argument("--restore-from", type=str, default=RESTORE_FROM,
                        help="Where restore model parameters from.")
    parser.add_argument("--save-num-images", type=int, default=SAVE_NUM_IMAGES,
                        help="How many images to save.")
    parser.add_argument("--save-pred-every", type=int, default=SAVE_PRED_EVERY,
                        help="Save summaries and checkpoint every often.")
    parser.add_argument("--snapshot-dir", type=str, default=SNAPSHOT_DIR,
                        help="Where to save snapshots of the model.")
    parser.add_argument("--weight-decay", type=float, default=WEIGHT_DECAY,
                        help="Regularisation parameter for L2-loss.")
    return parser.parse_args()
           

這個主要是為了傳入多個神經網絡的參數,參數待傳的參數可以提前設定好

BATCH_SIZE = 10
DATA_DIRECTORY = '/home/VOCdevkit'
DATA_LIST_PATH = './dataset/train.txt'
IGNORE_LABEL = 255
INPUT_SIZE = '321,321'
LEARNING_RATE = 2.5e-4
MOMENTUM = 0.9
NUM_CLASSES = 21
NUM_STEPS = 20001
POWER = 0.9
RANDOM_SEED = 1234
RESTORE_FROM = './deeplab_resnet.ckpt'
SAVE_NUM_IMAGES = 2
SAVE_PRED_EVERY = 1000
SNAPSHOT_DIR = './snapshots/'
WEIGHT_DECAY = 0.0005
           

這個子產品用的還是比較多的,但是不需要了解每個部分,隻需要了解簡單的傳參和參數設定就行了。