根据不同的文件使用不同的参数?

时间:2019-04-23 14:48:58

标签: python-3.x argparse

我有以下两个带有不同参数的函数

import argparse

def get_train_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('data_dir')
    parser.add_argument('--save_dir', type = str, default = 'checkpoints/', help = 'Save checkpoint directory')
    parser.add_argument('--arch', nargs='?', type = str, const = 'VGG', default = 'VGG', help = 'Select architecture. Choose VGG or AlexNet', choices=['VGG', 'AlexNet'])
    parser.add_argument('--learning_rate', type = float, default = '0.001', help = 'Select the model learning rate')
    parser.add_argument('--hidden_units', type = int, default = '1024', help = 'Select the model hidden units')
    parser.add_argument('--epochs', type = int, default = '2', help = 'Select the number of epochs')
    parser.add_argument('--gpu', nargs='?', type = str, const = 'gpu', default = 'gpu', help = 'Use GPU for training')

    return parser.parse_args()

def get_predict_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('single_image', nargs='?', const = 'flowers/test/1/image_06743.jpg')
    parser.add_argument('checkpoint')
    parser.add_argument('--top_k', type = int, default = '5', help = 'Select number of top propabilities')
    parser.add_argument('--category_names', nargs='?', type = dict, const = cat_to_name.json, default = cat_to_name.json, help = 'Select the model learning rate')
    parser.add_argument('--gpu', nargs='?', type = str, const = 'gpu', default = 'gpu', help = 'Use GPU for inference')

    return parser.parse_args()

我的问题是,当我尝试运行

  

python Forecast.py single_image检查点

我明白了

usage: predict.py [-h] [--save_dir SAVE_DIR] [--arch [{VGG,AlexNet}]]
                  [--learning_rate LEARNING_RATE]
                  [--hidden_units HIDDEN_UNITS] [--epochs EPOCHS]
                  [--gpu [GPU]]
                  data_dir
predict.py: error: unrecognized arguments: checkpoint

train.py中,我使用

  

从get_input_args导入get_train_args

运行get_train_args()

我有predict.py

from get_input_args import get_predict_args
from load_checkpoint import load_checkpoint
from train import cp_path

predict_arg = get_predict_args()

if predict_arg.gpu:
    device = 'cuda'
else:
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print('device:', device)

# Load checkpoint from saved path
load_checkpoint(cp_path, device)

组织代码以使每个参数集都可以基于终端中运行的文件可用的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

predict.py中,我正在使用

  

从train.py导入cp_path

这导致train.py在导入predict.py参数之前先运行。