python读取json格式的超参数
json文件:
{"full_finetuning": true,"max_len": 180,"learning_rate": 3e-5,"weight_decay": 0.01,"clip_grad": 2,"batch_size": 30,"epoch_num": 20,"min_epoch_num": 5,"patience": 0.02,"patience_num": 3
}
定义Params类:
class Params():def __init__(self, json_path):with open(json_path) as f:params = json.load(f)self.__dict__.update(params)def save(self, json_path):with open(json_path, 'w') as f:json.dump(self.__dict__, f, indent=4)def update(self, json_path):"""Loads parameters from json file"""with open(json_path) as f:params = json.load(f)self.__dict__.update(params)@propertydef dict(self):"""Gives dict-like access to Params instance by `params.dict['learning_rate']"""return self.__dict__
读取json配置文件:
params = Params(json_path)
定义的参数会以字典的形式存储在params对象中,可以通过对字典的访问方式访问params。