我正在运行一组不同的机器学习模型,我想创建一个可以在整个代码中发送的对象,其中存储模型参数和目录等内容,如下所示:
class model_parameters(object):
def __init__(self):
self.flags = {'clean': True,
'sampling': True}
self.dirs = {'inputs': '/inputs/',
'features': '/features/'}
这些参数大多数都是常量,但有些参数我需要在运行代码时修改,对于某些字典我还添加值。我对面向对象编程不够精通,首先不能说这是否是解决此问题的最佳方法,其次我将如何修改值,
例如将 dirs['features']
的值更改为 '/features/reduced/'
,
或添加值,例如向 dirs
添加键 'labels': '/labels/'
。
最佳答案
一般来说,这种方法是一种不错的方法,但除非 model_parameters
添加比这更多的信息,否则我会使用 namedtuple这更好地传达了您正在做的事情:
from collections import namedtuple
ModelParameters = namedtuple('ModelParameters', ['flags', 'dirs'])
model_parameters = ModelParameters(flags={'clean': True,
'sampling': True},
dirs={'inputs': '/inputs/',
'features': '/features/'})
然后您可以像这样修改值:
model_parameters.dirs['features'] = '/features/reduced/'
同样,添加值是通过分配给以前未分配的键来完成的:
model_parameters.dirs['labels'] = '/labels/'
关于python - 将模型参数存储在类中作为字典并修改/添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674744/