王权富贵:写python工程中配置文件的写法
生活随笔
收集整理的這篇文章主要介紹了
王权富贵:写python工程中配置文件的写法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
?
對應配置文件的初始
對應配置的更新函數
python接口的調用
?
對應配置文件的初始
#步驟1,導入對應庫 # `pip install easydict` if you don't have it from easydict import EasyDict as edict#步驟2,初始化 __C = edict()# Consumers can get config by: # from fast_rcnn_config import cfg #步驟3,重命名 cfg = __C# # Training options # #步驟4,對應類初始化 __C.TRAIN = edict()# Initial learning rate #步驟5,賦值 __C.TRAIN.LEARNING_RATE = 0.001 ............................................# # Testing options # __C.TEST = edict()# Scale to use during testing (can NOT list multiple scales) # The scale is the pixel size of an image's shortest side __C.TEST.SCALES = (600,)# Max pixel size of the longest side of a scaled input image __C.TEST.MAX_SIZE = 1000# Overlap threshold used for non-maximum suppression (suppress boxes with # IoU >= this threshold) __C.TEST.NMS = 0.3 ...............................................EasyDict可以讓你像訪問屬性一樣訪問dict里的變量
>>> from easydict import EasyDict as edict >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}}) >>> d.foo 3 >>> d.bar.x 1>>> d = edict(foo=3) >>> d.foo 3EasyDict庫詳細參考。
對應配置的更新函數
def _merge_a_into_b(a, b):"""Merge config dictionary a into config dictionary b, clobbering theoptions in b whenever they are also specified in a."""if type(a) is not edict:returnfor k, v in a.items():# a must specify keys that are in bif k not in b:raise KeyError('{} is not a valid config key'.format(k))# the types must match, tooold_type = type(b[k])if old_type is not type(v):if isinstance(b[k], np.ndarray):v = np.array(v, dtype=b[k].dtype)else:raise ValueError(('Type mismatch ({} vs. {}) ''for config key: {}').format(type(b[k]),type(v), k))# recursively merge dictsif type(v) is edict:try:_merge_a_into_b(a[k], b[k])except:print(('Error under config key: {}'.format(k)))raiseelse:b[k] = vdef cfg_from_file(filename):"""Load a config file and merge it into the default options."""import yamlwith open(filename, 'r') as f:yaml_cfg = edict(yaml.load(f))_merge_a_into_b(yaml_cfg, __C)def cfg_from_list(cfg_list):"""Set config keys via list (e.g., from command line)."""from ast import literal_evalassert len(cfg_list) % 2 == 0for k, v in zip(cfg_list[0::2], cfg_list[1::2]):key_list = k.split('.')d = __Cfor subkey in key_list[:-1]:assert subkey in dd = d[subkey]subkey = key_list[-1]assert subkey in dtry:value = literal_eval(v)except:# handle the case when v is a string literalvalue = vassert type(value) == type(d[subkey]), \'type {} does not match original type {}'.format(type(value), type(d[subkey]))d[subkey] = valuepython接口的調用
def parse_args():parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')parser.add_argument('--dataset', dest='dataset',help='training dataset',default='pascal_voc', type=str)..................................................args = parser.parse_args()return argsif __name__ == '__main__':args = parse_args()print('Called with args:')print(args)if args.cfg_file is not None:cfg_from_file(args.cfg_file)if args.set_cfgs is not None:cfg_from_list(args.set_cfgs)cfg.USE_GPU_NMS = args.cudaprint('Using config:')pprint.pprint(cfg)?
總結
以上是生活随笔為你收集整理的王权富贵:写python工程中配置文件的写法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【安装版】Win8.1专业版系统资源_I
- 下一篇: 怎么利用git管理/备份文件