假设存在以下参数:
parse = argparse.ArgumentParser()
parse.add_argument('--batch_size', type=int, default=50, help='the num of batch')
parse.add_argument('--epoches', type=int, default=5, help='the num of epoch')
parse.add_argument('--weight', type=str, default= '../output.pth', help='the path of pretrained model')
opt = parse.parse_args()
新建yaml文件如下:
batch_size: 32
epoches: 50
weights: "../...."
想要使用yaml新的参数运行脚本,需要将argparse空间中的参数更新,代码如下:
首先,声明命名空间
def dict2namespace(config):
namespace = argparse.Namespace()
for key, value in config.items():
if isinstance(value, dict):
new_value = dict2namespace(value)
else:
new_value = value
#将参数对添加到命名空间中
setattr(namespace, key, new_value)
return namespace
读入yaml文件中的参数
#配置参数
import yaml
with open('../***.yaml', 'r') as f:
default_arg = yaml.safe_load(f)
#args = parser.set_defaults(**default_arg)
args = dict2namespace({**vars(args), **default_arg}) #args为原脚本中的参数名,注意更改