跳到内容

基础核函数

smac.model.gaussian_process.kernels.base_kernels #

AbstractKernel #

AbstractKernel(
    *,
    operate_on: ndarray | None = None,
    has_conditions: bool = False,
    prior: AbstractPrior | None = None,
    **kwargs: Any
)

这是一个用于覆盖核函数功能的 mixin。由于它覆盖了核函数的功能,因此需要在继承层次结构中排在首位。正因为如此,不可能从核函数类中继承这个 Mixin,因为这将阻止其被实例化。因此,mypy 将无法识别与超类相关的任何内容,并且在访问超类中声明的成员(如 self.has_conditionsself._callsuper().get_params 等)时,需要添加一些 type:ignore 语句。

参数#

operate_on : np.ndarray, 默认为 None 在哪个 numpy 数组上进行操作。 has_conditions : bool, 默认为 False 核函数是否有条件。 prior : AbstractPrior, 默认为 None 核函数正在使用哪个先验。

属性#

operate_on : np.ndarray, 默认为 None 在哪个 numpy 数组上进行操作。 has_conditions : bool, 默认为 False 核函数是否有条件。可能由高斯过程改变。 prior : AbstractPrior, 默认为 None 核函数正在使用哪个先验。主要由 sklearn 使用。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def __init__(
    self,
    *,
    operate_on: np.ndarray | None = None,
    has_conditions: bool = False,
    prior: AbstractPrior | None = None,
    **kwargs: Any,
) -> None:
    self.operate_on = operate_on
    self.has_conditions = has_conditions
    self.prior = prior
    self._set_active_dims(operate_on)

    # Since this class is a mixin, we just pass all the other parameters to the next class.
    super().__init__(**kwargs)

    # Get variables from next class:
    # We make it explicit here to make sure the next class really has this attributes.
    self._hyperparameters: list[kernels.Hyperparameter] = super().hyperparameters  # type: ignore
    self._n_dims: int = super().n_dims  # type: ignore
    self._len_active: int | None

hyperparameters property #

hyperparameters: list[Hyperparameter]

返回所有超参数规范的列表。

meta property #

meta: dict[str, Any]

返回创建对象的元数据。此方法调用 get_params 方法来收集核函数的参数。

n_dims property #

n_dims: int

返回核函数的非固定超参数数量。

__call__ #

__call__(
    X: ndarray,
    Y: ndarray | None = None,
    eval_gradient: bool = False,
    active: ndarray | None = None,
) -> ndarray | tuple[ndarray, ndarray]

调用核函数。内部调用 self._call,该方法必须由子类指定。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def __call__(
    self,
    X: np.ndarray,
    Y: np.ndarray | None = None,
    eval_gradient: bool = False,
    active: np.ndarray | None = None,
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
    """Call the kernel function. Internally, `self._call` is called, which must be specified by a subclass."""
    if active is None and self.has_conditions:
        if self.operate_on is None:
            active = get_conditional_hyperparameters(X, Y)
        else:
            if Y is None:
                active = get_conditional_hyperparameters(X[:, self.operate_on], None)
            else:
                active = get_conditional_hyperparameters(X[:, self.operate_on], Y[:, self.operate_on])

    if self.operate_on is None:
        rval = self._call(X, Y, eval_gradient, active)
    else:
        if self._len_active is None:
            raise RuntimeError("The internal variable `_len_active` is not set.")

        if Y is None:
            rval = self._call(
                X=X[:, self.operate_on].reshape([-1, self._len_active]),
                Y=None,
                eval_gradient=eval_gradient,
                active=active,
            )
            X = X[:, self.operate_on].reshape((-1, self._len_active))
        else:
            rval = self._call(
                X=X[:, self.operate_on].reshape([-1, self._len_active]),
                Y=Y[:, self.operate_on].reshape([-1, self._len_active]),
                eval_gradient=eval_gradient,
                active=active,
            )
            X = X[:, self.operate_on].reshape((-1, self._len_active))
            Y = Y[:, self.operate_on].reshape((-1, self._len_active))

    return rval

get_params #

get_params(deep: bool = True) -> dict[str, Any]

获取此核函数的参数。

参数#

deep : bool, 默认为 True 如果为 True,将返回此估计器及其包含的子对象(也是估计器)的参数。

返回值#

params : dict[str, Any] 参数名映射到其值。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def get_params(self, deep: bool = True) -> dict[str, Any]:
    """Get parameters of this kernel.

    Parameters
    ----------
    deep : bool, defaults to True
        If True, will return the parameters for this estimator and
        contained subobjects that are estimators.

    Returns
    -------
    params : dict[str, Any]
        Parameter names mapped to their values.
    """
    params = {}

    # ignore[misc] looks like it catches all kinds of errors, but misc is actually a category from mypy:
    # https://mypy.readthedocs.io/en/latest/error_code_list.html#miscellaneous-checks-misc
    tmp = super().get_params(deep)  # type: ignore[misc] # noqa F821
    args = list(tmp.keys())

    # Sum and Product do not clone the 'has_conditions' attribute by default. Instead of changing their
    # get_params() method, we simply add the attribute here!
    if "has_conditions" not in args:
        args.append("has_conditions")

    for arg in args:
        params[arg] = getattr(self, arg, None)

    return params

ConstantKernel #

ConstantKernel(
    constant_value: float = 1.0,
    constant_value_bounds: tuple[float, float] = (
        1e-05,
        100000.0,
    ),
    operate_on: ndarray | None = None,
    has_conditions: bool = False,
    prior: AbstractPrior | None = None,
)

基类: AbstractKernel, ConstantKernel

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def __init__(
    self,
    constant_value: float = 1.0,
    constant_value_bounds: tuple[float, float] = (1e-5, 1e5),
    operate_on: np.ndarray | None = None,
    has_conditions: bool = False,
    prior: AbstractPrior | None = None,
) -> None:
    super().__init__(
        operate_on=operate_on,
        has_conditions=has_conditions,
        prior=prior,
        constant_value=constant_value,
        constant_value_bounds=constant_value_bounds,
    )

hyperparameters property #

hyperparameters: list[Hyperparameter]

返回所有超参数规范的列表。

meta property #

meta: dict[str, Any]

返回创建对象的元数据。此方法调用 get_params 方法来收集核函数的参数。

n_dims property #

n_dims: int

返回核函数的非固定超参数数量。

__call__ #

__call__(
    X: ndarray,
    Y: ndarray | None = None,
    eval_gradient: bool = False,
    active: ndarray | None = None,
) -> ndarray | tuple[ndarray, ndarray]

返回核函数 k(X, Y) 以及可选的其梯度。

参数#

X : np.ndarray, 形状 (n_samples_X, n_features) 返回的核函数 k(X, Y) 的左参数。

np.ndarray, 形状 (n_samples_Y, n_features), (可选, 默认为 None)

返回的核函数 k(X, Y) 的右参数。如果为 None,则计算 k(X, X)。

bool (可选, 默认为 False)

确定是否计算相对于核函数超参数的梯度。仅在 Y 为 None 时支持。

np.ndarray (n_samples_X, n_features) (可选)

布尔数组,指定哪些超参数是活动的。

返回值#

K : np.ndarray, 形状 (n_samples_X, n_samples_Y) 核函数 k(X, Y)。

np.ndarray (可选), 形状 (n_samples_X, n_samples_X, n_dims)

核函数 k(X, X) 相对于核函数超参数的梯度。仅当 eval_gradient 为 True 时返回。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def __call__(
    self,
    X: np.ndarray,
    Y: np.ndarray | None = None,
    eval_gradient: bool = False,
    active: np.ndarray | None = None,
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
    """Return the kernel k(X, Y) and optionally its gradient.

    Parameters
    ----------
    X : np.ndarray, shape (n_samples_X, n_features)
        Left argument of the returned kernel k(X, Y).

    Y : np.ndarray, shape (n_samples_Y, n_features), (optional, default=None)
        Right argument of the returned kernel k(X, Y). If None, k(X, X)
        is evaluated instead.

    eval_gradient : bool (optional, default=False)
        Determines whether the gradient with respect to the kernel
        hyperparameter is determined. Only supported when Y is None.

    active : np.ndarray (n_samples_X, n_features) (optional)
        Boolean array specifying which hyperparameters are active.

    Returns
    -------
    K : np.ndarray, shape (n_samples_X, n_samples_Y)
        Kernel k(X, Y).

    K_gradient : np.ndarray (opt.), shape (n_samples_X, n_samples_X, n_dims)
        The gradient of the kernel k(X, X) with respect to the
        hyperparameter of the kernel. Only returned when eval_gradient
        is True.
    """
    X = np.atleast_2d(X)
    if Y is None:
        Y = X
    elif eval_gradient:
        raise ValueError("Gradient can only be evaluated when Y is None.")

    K = np.full(
        (X.shape[0], Y.shape[0]),
        self.constant_value,
        dtype=np.array(self.constant_value).dtype,
    )
    if eval_gradient:
        if not self.hyperparameter_constant_value.fixed:
            return (
                K,
                np.full(
                    (X.shape[0], X.shape[0], 1),
                    self.constant_value,
                    dtype=np.array(self.constant_value).dtype,
                ),
            )
        else:
            return K, np.empty((X.shape[0], X.shape[0], 0))
    else:
        return K

get_params #

get_params(deep: bool = True) -> dict[str, Any]

获取此核函数的参数。

参数#

deep : bool, 默认为 True 如果为 True,将返回此估计器及其包含的子对象(也是估计器)的参数。

返回值#

params : dict[str, Any] 参数名映射到其值。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def get_params(self, deep: bool = True) -> dict[str, Any]:
    """Get parameters of this kernel.

    Parameters
    ----------
    deep : bool, defaults to True
        If True, will return the parameters for this estimator and
        contained subobjects that are estimators.

    Returns
    -------
    params : dict[str, Any]
        Parameter names mapped to their values.
    """
    params = {}

    # ignore[misc] looks like it catches all kinds of errors, but misc is actually a category from mypy:
    # https://mypy.readthedocs.io/en/latest/error_code_list.html#miscellaneous-checks-misc
    tmp = super().get_params(deep)  # type: ignore[misc] # noqa F821
    args = list(tmp.keys())

    # Sum and Product do not clone the 'has_conditions' attribute by default. Instead of changing their
    # get_params() method, we simply add the attribute here!
    if "has_conditions" not in args:
        args.append("has_conditions")

    for arg in args:
        params[arg] = getattr(self, arg, None)

    return params

ProductKernel #

ProductKernel(
    k1: Kernel,
    k2: Kernel,
    operate_on: ndarray | None = None,
    has_conditions: bool = False,
)

基类: AbstractKernel, Product

乘积核实现。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def __init__(
    self,
    k1: kernels.Kernel,
    k2: kernels.Kernel,
    operate_on: np.ndarray | None = None,
    has_conditions: bool = False,
) -> None:
    super().__init__(
        operate_on=operate_on,
        has_conditions=has_conditions,
        k1=k1,
        k2=k2,
    )

hyperparameters property #

hyperparameters: list[Hyperparameter]

返回所有超参数规范的列表。

meta property #

meta: dict[str, Any]

返回创建对象的元数据。此方法调用 get_params 方法来收集核函数的参数。

n_dims property #

n_dims: int

返回核函数的非固定超参数数量。

__call__ #

__call__(
    X: ndarray,
    Y: ndarray | None = None,
    eval_gradient: bool = False,
    active: ndarray | None = None,
) -> ndarray | tuple[ndarray, ndarray]

返回核函数 k(X, Y) 以及可选的其梯度。

参数#

X : np.ndarray, 形状 (n_samples_X, n_features) 返回的核函数 k(X, Y) 的左参数。

np.ndarray, 形状 (n_samples_Y, n_features), (可选, 默认为 None)

返回的核函数 k(X, Y) 的右参数。如果为 None,则计算 k(X, X)。

bool (可选, 默认为 False)

确定是否计算相对于核函数超参数的梯度。

np.ndarray (n_samples_X, n_features) (可选)

布尔数组,指定哪些超参数是活动的。

返回值#

K : np.ndarray, 形状 (n_samples_X, n_samples_Y) 核函数 k(X, Y)。

np.ndarray (可选), 形状 (n_samples_X, n_samples_X, n_dims)

核函数 k(X, X) 相对于核函数超参数的梯度。仅当 eval_gradient 为 True 时返回。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def __call__(
    self,
    X: np.ndarray,
    Y: np.ndarray | None = None,
    eval_gradient: bool = False,
    active: np.ndarray | None = None,
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
    """Return the kernel k(X, Y) and optionally its gradient.

    Parameters
    ----------
    X : np.ndarray, shape (n_samples_X, n_features)
        Left argument of the returned kernel k(X, Y).

    Y : np.ndarray, shape (n_samples_Y, n_features), (optional, default=None)
        Right argument of the returned kernel k(X, Y). If None, k(X, X)
        is evaluated instead.

    eval_gradient : bool (optional, default=False)
        Determines whether the gradient with respect to the kernel
        hyperparameter is determined.

    active : np.ndarray (n_samples_X, n_features) (optional)
        Boolean array specifying which hyperparameters are active.

    Returns
    -------
    K : np.ndarray, shape (n_samples_X, n_samples_Y)
        Kernel k(X, Y).

    K_gradient : np.ndarray (opt.), shape (n_samples_X, n_samples_X, n_dims)
        The gradient of the kernel k(X, X) with respect to the
        hyperparameter of the kernel. Only returned when eval_gradient
        is True.
    """
    if eval_gradient:
        K1, K1_gradient = self.k1(X, Y, eval_gradient=True, active=active)
        K2, K2_gradient = self.k2(X, Y, eval_gradient=True, active=active)

        return K1 * K2, np.dstack((K1_gradient * K2[:, :, np.newaxis], K2_gradient * K1[:, :, np.newaxis]))
    else:
        return self.k1(X, Y, active=active) * self.k2(X, Y, active=active)

get_params #

get_params(deep: bool = True) -> dict[str, Any]

获取此核函数的参数。

参数#

deep : bool, 默认为 True 如果为 True,将返回此估计器及其包含的子对象(也是估计器)的参数。

返回值#

params : dict[str, Any] 参数名映射到其值。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def get_params(self, deep: bool = True) -> dict[str, Any]:
    """Get parameters of this kernel.

    Parameters
    ----------
    deep : bool, defaults to True
        If True, will return the parameters for this estimator and
        contained subobjects that are estimators.

    Returns
    -------
    params : dict[str, Any]
        Parameter names mapped to their values.
    """
    params = {}

    # ignore[misc] looks like it catches all kinds of errors, but misc is actually a category from mypy:
    # https://mypy.readthedocs.io/en/latest/error_code_list.html#miscellaneous-checks-misc
    tmp = super().get_params(deep)  # type: ignore[misc] # noqa F821
    args = list(tmp.keys())

    # Sum and Product do not clone the 'has_conditions' attribute by default. Instead of changing their
    # get_params() method, we simply add the attribute here!
    if "has_conditions" not in args:
        args.append("has_conditions")

    for arg in args:
        params[arg] = getattr(self, arg, None)

    return params

SumKernel #

SumKernel(
    k1: Kernel,
    k2: Kernel,
    operate_on: ndarray | None = None,
    has_conditions: bool = False,
)

基类: AbstractKernel, Sum

求和核实现。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def __init__(
    self,
    k1: kernels.Kernel,
    k2: kernels.Kernel,
    operate_on: np.ndarray | None = None,
    has_conditions: bool = False,
) -> None:
    super().__init__(
        operate_on=operate_on,
        has_conditions=has_conditions,
        k1=k1,
        k2=k2,
    )

hyperparameters property #

hyperparameters: list[Hyperparameter]

返回所有超参数规范的列表。

meta property #

meta: dict[str, Any]

返回创建对象的元数据。此方法调用 get_params 方法来收集核函数的参数。

n_dims property #

n_dims: int

返回核函数的非固定超参数数量。

__call__ #

__call__(
    X: ndarray,
    Y: ndarray | None = None,
    eval_gradient: bool = False,
    active: ndarray | None = None,
) -> ndarray | tuple[ndarray, ndarray]

返回核函数 k(X, Y) 以及可选的其梯度。

参数#

X : np.ndarray, 形状 (n_samples_X, n_features) 返回的核函数 k(X, Y) 的左参数。

np.ndarray, 形状 (n_samples_Y, n_features), (可选, 默认为 None)

返回的核函数 k(X, Y) 的右参数。如果为 None,则计算 k(X, X)。

bool (可选, 默认为 False)

确定是否计算相对于核函数超参数的梯度。

np.ndarray (n_samples_X, n_features) (可选)

布尔数组,指定哪些超参数是活动的。

返回值#

K : np.ndarray, 形状 (n_samples_X, n_samples_Y) 核函数 k(X, Y)。

np.ndarray (可选), 形状 (n_samples_X, n_samples_X, n_dims)

核函数 k(X, X) 相对于核函数超参数的梯度。仅当 eval_gradient 为 True 时返回。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def __call__(
    self,
    X: np.ndarray,
    Y: np.ndarray | None = None,
    eval_gradient: bool = False,
    active: np.ndarray | None = None,
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
    """Return the kernel k(X, Y) and optionally its gradient.

    Parameters
    ----------
    X : np.ndarray, shape (n_samples_X, n_features)
        Left argument of the returned kernel k(X, Y).

    Y : np.ndarray, shape (n_samples_Y, n_features), (optional, default=None)
        Right argument of the returned kernel k(X, Y). If None, k(X, X)
        is evaluated instead.

    eval_gradient : bool (optional, default=False)
        Determines whether the gradient with respect to the kernel
        hyperparameter is determined.

    active : np.ndarray (n_samples_X, n_features) (optional)
        Boolean array specifying which hyperparameters are active.

    Returns
    -------
    K : np.ndarray, shape (n_samples_X, n_samples_Y)
        Kernel k(X, Y).

    K_gradient : np.ndarray (opt.), shape (n_samples_X, n_samples_X, n_dims)
        The gradient of the kernel k(X, X) with respect to the
        hyperparameter of the kernel. Only returned when eval_gradient
        is True.
    """
    if eval_gradient:
        K1, K1_gradient = self.k1(X, Y, eval_gradient=True, active=active)
        K2, K2_gradient = self.k2(X, Y, eval_gradient=True, active=active)

        return K1 + K2, np.dstack((K1_gradient, K2_gradient))
    else:
        return self.k1(X, Y, active=active) + self.k2(X, Y, active=active)

get_params #

get_params(deep: bool = True) -> dict[str, Any]

获取此核函数的参数。

参数#

deep : bool, 默认为 True 如果为 True,将返回此估计器及其包含的子对象(也是估计器)的参数。

返回值#

params : dict[str, Any] 参数名映射到其值。

源代码位于 smac/model/gaussian_process/kernels/base_kernels.py
def get_params(self, deep: bool = True) -> dict[str, Any]:
    """Get parameters of this kernel.

    Parameters
    ----------
    deep : bool, defaults to True
        If True, will return the parameters for this estimator and
        contained subobjects that are estimators.

    Returns
    -------
    params : dict[str, Any]
        Parameter names mapped to their values.
    """
    params = {}

    # ignore[misc] looks like it catches all kinds of errors, but misc is actually a category from mypy:
    # https://mypy.readthedocs.io/en/latest/error_code_list.html#miscellaneous-checks-misc
    tmp = super().get_params(deep)  # type: ignore[misc] # noqa F821
    args = list(tmp.keys())

    # Sum and Product do not clone the 'has_conditions' attribute by default. Instead of changing their
    # get_params() method, we simply add the attribute here!
    if "has_conditions" not in args:
        args.append("has_conditions")

    for arg in args:
        params[arg] = getattr(self, arg, None)

    return params