为了提高程序的灵活性,一种推荐的方式是将代码的可配置项抽出为单个源文件,以方便统一修改查看:
"""
config.py 配置文件
"""
NETWORK_SIZE = 200
DS_SIZE = [0.01, 10]
CAPACITY_RATIO = 5
CL_CL_DELAY_BASELINE = [2e-3, 100e-3]
DC_DC_DELAY_BASELINE = [5e-3, 50e-3]
CL_DC_DELAY_BASELINE = [10e-3, 200e-3]
# ......
但随着程序的反复修改,逐渐难以将当时保存的模型和匹配的配置一一对应,从而带来很多麻烦,一个自然的想法是将配置一起保存下来:
"""
config.py 配置文件
"""
NETWORK_SIZE = 200
DS_SIZE = [0.01, 10]
CAPACITY_RATIO = 5
CL_CL_DELAY_BASELINE = [2e-3, 100e-3]
DC_DC_DELAY_BASELINE = [5e-3, 50e-3]
CL_DC_DELAY_BASELINE = [10e-3, 200e-3]
# ......
# 以上是模型配置
def state_dict():
"""返回config字典"""
import config
from inspect import isfunction, ismodule
state = {}
vrb_names = dir(config)
for vrbName in vrb_names:
if vrbName.startswith('__') and vrbName.endswith('__'):
continue
vrb = getattr(config, vrbName)
if isfunction(vrb) or ismodule(vrb):
continue
state[vrbName] = vrb
return state
def load(state_dict):
"""加载config字典"""
import config
for vrbName in state_dict:
setattr(config, vrbName, state_dict[vrbName])
print('config loaded')
def output():
"""打印参数字典"""
stat = state_dict()
for vrb_name in stat:
print(vrb_name + ' = ' + str(stat[vrb_name]))
if __name__ == '__main__':
output()
这样所有在配置文件中定义的配置变量均可以读取为字典:
import config as cfg
dic = cfg.state_dict()
print(dic)
# 输出:
# {'CAPACITY_RATIO': 5, 'CL_CL_DELAY_BASELINE': [0.002, 0.1], 'CL_DC_DELAY_BASELINE': [0.01, 0.2], 'DC_DC_DELAY_BASELINE': [0.005, 0.05], 'DS_SIZE': [0.01, 10], 'NETWORK_SIZE': 200}
然后就可以使用持久化方法进行存取,如 np.savez_compressed()
和 np.load()
,还可以将 cfg.state_dict()
赋值给Model的成员变量,对整个Model对象存取的同时也存取了配置。
最后可以在需要时将配置进行还原:
import config as cfg
cfg.load(model.cfg_dict)
之后我们看下是否将配置恢复回来了,调用 config.py
的 output()
函数输出一下看看:
cfg.output()
# 输出:
# CAPACITY_RATIO = 5
# CL_CL_DELAY_BASELINE = [0.002, 0.1]
# CL_DC_DELAY_BASELINE = [0.01, 0.2]
# DC_DC_DELAY_BASELINE = [0.005, 0.05]
# DS_SIZE = [0.01, 10]
# NETWORK_SIZE = 200