设置

示例用法

# Simple getting and setting.
print(pyro.settings.get())  # print all settings
print(pyro.settings.get("cholesky_relative_jitter"))  # print one
pyro.settings.set(cholesky_relative_jitter=0.5)  # set one
pyro.settings.set(**my_settings)  # set many

# Use as a contextmanager.
with pyro.settings.context(cholesky_relative_jitter=0.5):
    my_function()

# Use as a decorator.
fn = pyro.settings.context(cholesky_relative_jitter=0.5)(my_function)
fn()

# Register a new setting.
pyro.settings.register(
    "binomial_approx_sample_thresh",  # alias
    "pyro.distributions.torch",       # module
    "Binomial.approx_sample_thresh",  # deep name
)

# Register a new setting on a user-provided validator.
@pyro.settings.register(
    "binomial_approx_sample_thresh",  # alias
    "pyro.distributions.torch",       # module
    "Binomial.approx_sample_thresh",  # deep name
)
def validate_thresh(thresh):  # called each time setting is set
    assert isinstance(thresh, float)
    assert thresh > 0

默认设置

  • binomial_approx_log_prob_tol = 0.0

  • binomial_approx_sample_thresh = inf

  • cholesky_relative_jitter = 4.0

  • module_local_params = False

  • validate_distributions_pyro = True

  • validate_distributions_torch = True

  • validate_infer = True

  • validate_poutine = True

设置接口

get(alias: Optional[str] = None) Any[source]

获取一个或所有全局设置。

参数

alias (str) – 已注册设置的名称。

返回

当前设置的值。

set(**kwargs) None[source]

设置一个或多个设置。

参数

**kwargs – alias=value 对。

context(**kwargs) Iterator[None][source]

用于临时覆盖一个或多个设置的上下文管理器。这也可以作为装饰器使用。

参数

**kwargs – alias=value 对。

register(alias: str, modulename: str, deepname: str, validator: Optional[Callable] = None) Callable[source]

注册一个全局设置。

这应该在定义设置的模块中声明。

这可以用作声明

settings.register("my_setting", __name__, "MY_SETTING")

或用作用户定义验证器函数的装饰器

@settings.register("my_setting", __name__, "MY_SETTING")
def _validate_my_setting(value):
    assert isinstance(value, float)
    assert 0 < value
参数
  • alias (str) – 一个有效的 Python 标识符,用作设置别名。建议使用小写蛇形命名法,例如 my_setting

  • modulename (str) – 声明设置的模块名称,通常为 __name__

  • deepname (str) – 一个由 . 分隔的名称字符串。例如,对于模块常量,使用 MY_CONSTANT。对于类属性,使用 MyClass.my_attribute

  • validator (callable) – 可选的验证器,它接收一个值,可能会引发验证错误,并返回 None。