Skip to content

Unconstrained

gpplus.kernels.unconstrained_kernel.UnconstrainedKernel ¤

Bases: Kernel

Source code in gpplus/kernels/unconstrained_kernel.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
class UnconstrainedKernel(Kernel):
    has_lengthscale = False

    def __init__(
        self,
        ard_num_dims: Optional[int] = None,
        batch_shape: Optional[torch.Size] = None,
        active_dims: Optional[Tuple[int, ...]] = None,
        lengthscale_prior: Optional[Prior] = None,
        lengthscale_constraint: Optional[SoftClamp] = None,
        eps: float = 1e-6,
        **kwargs,
    ):
        super(Kernel, self).__init__()  # Call Module's __init__ and Skip Kernel's __init__
        self._batch_shape = torch.Size([]) if batch_shape is None else batch_shape
        if active_dims is not None and not torch.is_tensor(active_dims):
            active_dims = torch.tensor(active_dims, dtype=torch.long)
        self.register_buffer("active_dims", active_dims)
        self.ard_num_dims = ard_num_dims

        self.eps = eps

        param_transform = kwargs.get("param_transform")

        if lengthscale_constraint is None:
            lengthscale_constraint = SoftClamp(lower_bound=-5, upper_bound=3, margin=1e-2)
            # lengthscale_constraint = gpytorch.constraints.Interval(lower_bound=-5, upper_bound=3)

        if param_transform is not None:
            # warnings.warn(
            #     "The 'param_transform' argument is now deprecated. If you want to use a different "
            #     "transformation, specify a different 'lengthscale_constraint' instead.",
            #     DeprecationWarning,
            # )
            warnings.warn(
                "The 'param_transform' argument is now deprecated.",
                DeprecationWarning,
            )

        if self.has_lengthscale:
            lengthscale_num_dims = 1 if ard_num_dims is None else ard_num_dims
            self.register_parameter(
                name="raw_lengthscale",
                parameter=torch.nn.Parameter(torch.zeros(*self.batch_shape, 1, lengthscale_num_dims)),
            )
            if lengthscale_prior is not None:
                if not isinstance(lengthscale_prior, Prior):
                    raise TypeError("Expected gpytorch.priors.Prior but got " + type(lengthscale_prior).__name__)
                self.register_prior(
                    "lengthscale_prior", lengthscale_prior, self._lengthscale_param, self._lengthscale_closure
                )
                # self.register_prior("lengthscale_prior", lengthscale_prior, "lengthscale")

            self.register_constraint("raw_lengthscale", lengthscale_constraint)

        self.distance_module = None
        # TODO: Remove this on next official PyTorch release.
        self.__pdist_supports_batch = True

    def covar_dist(
        self,
        x1: Tensor,
        x2: Tensor,
        diag: bool = False,
        last_dim_is_batch: bool = False,
        # square_dist: bool = False,
        ord: float = 2,
        **params,
    ) -> Tensor:
        r"""
        This is a helper method for computing the Euclidean distance between
        all pairs of points in :math:`\mathbf x_1` and :math:`\mathbf x_2`.

        :param x1: First set of data (... x N x D).
        :param x2: Second set of data (... x M x D).
        :param diag: Should the Kernel compute the whole kernel, or just the diag?
            If True, it must be the case that `x1 == x2`. (Default: False.)
        :param last_dim_is_batch: If True, treat the last dimension
            of `x1` and `x2` as another batch dimension.
            (Useful for additive structure over the dimensions). (Default: False.)
        :param square_dist:
            If True, returns the squared distance rather than the standard distance. (Default: False.)
        :return: The kernel matrix or vector. The shape depends on the kernel's evaluation mode:

            * `full_covar`: `... x N x M`
            * `full_covar` with `last_dim_is_batch=True`: `... x K x N x M`
            * `diag`: `... x N`
            * `diag` with `last_dim_is_batch=True`: `... x K x N`
        """
        if last_dim_is_batch:
            x1 = x1.transpose(-1, -2).unsqueeze(-1)
            x2 = x2.transpose(-1, -2).unsqueeze(-1)

        x1_eq_x2 = torch.equal(x1, x2)
        res = None

        if diag:
            # Special case the diagonal because we can return all zeros most of the time.
            if x1_eq_x2:
                return torch.zeros(*x1.shape[:-2], x1.shape[-2], dtype=x1.dtype, device=x1.device)
            else:
                res = torch.linalg.norm(x1 - x2, dim=-1, ord=ord)
                return res.pow(ord)
        else:
            res = torch.cdist(x1, x2, p=ord).clamp_min(1e-15)
            return res.pow(ord)
has_lengthscale = False class-attribute instance-attribute ¤
ard_num_dims = ard_num_dims instance-attribute ¤
eps = eps instance-attribute ¤
distance_module = None instance-attribute ¤
__pdist_supports_batch = True instance-attribute ¤
__init__(ard_num_dims: Optional[int] = None, batch_shape: Optional[torch.Size] = None, active_dims: Optional[Tuple[int, ...]] = None, lengthscale_prior: Optional[Prior] = None, lengthscale_constraint: Optional[SoftClamp] = None, eps: float = 1e-06, **kwargs) ¤
Source code in gpplus/kernels/unconstrained_kernel.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def __init__(
    self,
    ard_num_dims: Optional[int] = None,
    batch_shape: Optional[torch.Size] = None,
    active_dims: Optional[Tuple[int, ...]] = None,
    lengthscale_prior: Optional[Prior] = None,
    lengthscale_constraint: Optional[SoftClamp] = None,
    eps: float = 1e-6,
    **kwargs,
):
    super(Kernel, self).__init__()  # Call Module's __init__ and Skip Kernel's __init__
    self._batch_shape = torch.Size([]) if batch_shape is None else batch_shape
    if active_dims is not None and not torch.is_tensor(active_dims):
        active_dims = torch.tensor(active_dims, dtype=torch.long)
    self.register_buffer("active_dims", active_dims)
    self.ard_num_dims = ard_num_dims

    self.eps = eps

    param_transform = kwargs.get("param_transform")

    if lengthscale_constraint is None:
        lengthscale_constraint = SoftClamp(lower_bound=-5, upper_bound=3, margin=1e-2)
        # lengthscale_constraint = gpytorch.constraints.Interval(lower_bound=-5, upper_bound=3)

    if param_transform is not None:
        # warnings.warn(
        #     "The 'param_transform' argument is now deprecated. If you want to use a different "
        #     "transformation, specify a different 'lengthscale_constraint' instead.",
        #     DeprecationWarning,
        # )
        warnings.warn(
            "The 'param_transform' argument is now deprecated.",
            DeprecationWarning,
        )

    if self.has_lengthscale:
        lengthscale_num_dims = 1 if ard_num_dims is None else ard_num_dims
        self.register_parameter(
            name="raw_lengthscale",
            parameter=torch.nn.Parameter(torch.zeros(*self.batch_shape, 1, lengthscale_num_dims)),
        )
        if lengthscale_prior is not None:
            if not isinstance(lengthscale_prior, Prior):
                raise TypeError("Expected gpytorch.priors.Prior but got " + type(lengthscale_prior).__name__)
            self.register_prior(
                "lengthscale_prior", lengthscale_prior, self._lengthscale_param, self._lengthscale_closure
            )
            # self.register_prior("lengthscale_prior", lengthscale_prior, "lengthscale")

        self.register_constraint("raw_lengthscale", lengthscale_constraint)

    self.distance_module = None
    # TODO: Remove this on next official PyTorch release.
    self.__pdist_supports_batch = True
covar_dist(x1: Tensor, x2: Tensor, diag: bool = False, last_dim_is_batch: bool = False, ord: float = 2, **params) -> Tensor ¤

This is a helper method for computing the Euclidean distance between all pairs of points in :math:\mathbf x_1 and :math:\mathbf x_2.

:param x1: First set of data (... x N x D). :param x2: Second set of data (... x M x D). :param diag: Should the Kernel compute the whole kernel, or just the diag? If True, it must be the case that x1 == x2. (Default: False.) :param last_dim_is_batch: If True, treat the last dimension of x1 and x2 as another batch dimension. (Useful for additive structure over the dimensions). (Default: False.) :param square_dist: If True, returns the squared distance rather than the standard distance. (Default: False.) :return: The kernel matrix or vector. The shape depends on the kernel's evaluation mode:

* `full_covar`: `... x N x M`
* `full_covar` with `last_dim_is_batch=True`: `... x K x N x M`
* `diag`: `... x N`
* `diag` with `last_dim_is_batch=True`: `... x K x N`
Source code in gpplus/kernels/unconstrained_kernel.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def covar_dist(
    self,
    x1: Tensor,
    x2: Tensor,
    diag: bool = False,
    last_dim_is_batch: bool = False,
    # square_dist: bool = False,
    ord: float = 2,
    **params,
) -> Tensor:
    r"""
    This is a helper method for computing the Euclidean distance between
    all pairs of points in :math:`\mathbf x_1` and :math:`\mathbf x_2`.

    :param x1: First set of data (... x N x D).
    :param x2: Second set of data (... x M x D).
    :param diag: Should the Kernel compute the whole kernel, or just the diag?
        If True, it must be the case that `x1 == x2`. (Default: False.)
    :param last_dim_is_batch: If True, treat the last dimension
        of `x1` and `x2` as another batch dimension.
        (Useful for additive structure over the dimensions). (Default: False.)
    :param square_dist:
        If True, returns the squared distance rather than the standard distance. (Default: False.)
    :return: The kernel matrix or vector. The shape depends on the kernel's evaluation mode:

        * `full_covar`: `... x N x M`
        * `full_covar` with `last_dim_is_batch=True`: `... x K x N x M`
        * `diag`: `... x N`
        * `diag` with `last_dim_is_batch=True`: `... x K x N`
    """
    if last_dim_is_batch:
        x1 = x1.transpose(-1, -2).unsqueeze(-1)
        x2 = x2.transpose(-1, -2).unsqueeze(-1)

    x1_eq_x2 = torch.equal(x1, x2)
    res = None

    if diag:
        # Special case the diagonal because we can return all zeros most of the time.
        if x1_eq_x2:
            return torch.zeros(*x1.shape[:-2], x1.shape[-2], dtype=x1.dtype, device=x1.device)
        else:
            res = torch.linalg.norm(x1 - x2, dim=-1, ord=ord)
            return res.pow(ord)
    else:
        res = torch.cdist(x1, x2, p=ord).clamp_min(1e-15)
        return res.pow(ord)

gpplus.kernels.power_exponential_kernel.PowerExponentialKernel ¤

Bases: UnconstrainedKernel

Source code in gpplus/kernels/power_exponential_kernel.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class PowerExponentialKernel(UnconstrainedKernel):
    has_lengthscale = True  # Enable lengthscale functionality
    is_stationary = True  # The kernel is stationary

    def __init__(self, **kwargs):
        # power is the exponent parameter (κ)
        super().__init__(**kwargs)
        # Register the power parameter (as a raw parameter to allow constraints)
        self.register_parameter(
            name="raw_power",
            parameter=torch.nn.Parameter(torch.zeros(*self.batch_shape, 1, 1)),
        )

        # Constrain raw_power to be in the interval [1, 2]
        self.register_constraint("raw_power", Interval(1.0, 2.0))

    @property
    def power(self):
        # Transform raw_power via the constraint's transformation.
        return self.raw_power_constraint.transform(self.raw_power)

    @power.setter
    def power(self, value):
        self._set_power(value)

    def _set_power(self, value):
        if not torch.is_tensor(value):
            value = torch.as_tensor(value).to(self.raw_power)
        # Use the inverse transform to set the raw parameter value
        self.initialize(raw_power=self.raw_power_constraint.inverse_transform(value))

    def forward(self, x1, x2, diag=False, **params):
        scaling_factors = torch.pow(10, self.lengthscale / self.power)

        x1_ = x1.mul(scaling_factors)
        x2_ = x2.mul(scaling_factors)

        return postprocess_(self.covar_dist(x1_, x2_, ord=self.power.item(), diag=diag, **params))
has_lengthscale = True class-attribute instance-attribute ¤
is_stationary = True class-attribute instance-attribute ¤
power property writable ¤
ard_num_dims = ard_num_dims instance-attribute ¤
eps = eps instance-attribute ¤
distance_module = None instance-attribute ¤
__pdist_supports_batch = True instance-attribute ¤
__init__(**kwargs) ¤
Source code in gpplus/kernels/power_exponential_kernel.py
37
38
39
40
41
42
43
44
45
46
47
def __init__(self, **kwargs):
    # power is the exponent parameter (κ)
    super().__init__(**kwargs)
    # Register the power parameter (as a raw parameter to allow constraints)
    self.register_parameter(
        name="raw_power",
        parameter=torch.nn.Parameter(torch.zeros(*self.batch_shape, 1, 1)),
    )

    # Constrain raw_power to be in the interval [1, 2]
    self.register_constraint("raw_power", Interval(1.0, 2.0))
forward(x1, x2, diag=False, **params) ¤
Source code in gpplus/kernels/power_exponential_kernel.py
64
65
66
67
68
69
70
def forward(self, x1, x2, diag=False, **params):
    scaling_factors = torch.pow(10, self.lengthscale / self.power)

    x1_ = x1.mul(scaling_factors)
    x2_ = x2.mul(scaling_factors)

    return postprocess_(self.covar_dist(x1_, x2_, ord=self.power.item(), diag=diag, **params))
covar_dist(x1: Tensor, x2: Tensor, diag: bool = False, last_dim_is_batch: bool = False, ord: float = 2, **params) -> Tensor ¤

This is a helper method for computing the Euclidean distance between all pairs of points in :math:\mathbf x_1 and :math:\mathbf x_2.

:param x1: First set of data (... x N x D). :param x2: Second set of data (... x M x D). :param diag: Should the Kernel compute the whole kernel, or just the diag? If True, it must be the case that x1 == x2. (Default: False.) :param last_dim_is_batch: If True, treat the last dimension of x1 and x2 as another batch dimension. (Useful for additive structure over the dimensions). (Default: False.) :param square_dist: If True, returns the squared distance rather than the standard distance. (Default: False.) :return: The kernel matrix or vector. The shape depends on the kernel's evaluation mode:

* `full_covar`: `... x N x M`
* `full_covar` with `last_dim_is_batch=True`: `... x K x N x M`
* `diag`: `... x N`
* `diag` with `last_dim_is_batch=True`: `... x K x N`
Source code in gpplus/kernels/unconstrained_kernel.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def covar_dist(
    self,
    x1: Tensor,
    x2: Tensor,
    diag: bool = False,
    last_dim_is_batch: bool = False,
    # square_dist: bool = False,
    ord: float = 2,
    **params,
) -> Tensor:
    r"""
    This is a helper method for computing the Euclidean distance between
    all pairs of points in :math:`\mathbf x_1` and :math:`\mathbf x_2`.

    :param x1: First set of data (... x N x D).
    :param x2: Second set of data (... x M x D).
    :param diag: Should the Kernel compute the whole kernel, or just the diag?
        If True, it must be the case that `x1 == x2`. (Default: False.)
    :param last_dim_is_batch: If True, treat the last dimension
        of `x1` and `x2` as another batch dimension.
        (Useful for additive structure over the dimensions). (Default: False.)
    :param square_dist:
        If True, returns the squared distance rather than the standard distance. (Default: False.)
    :return: The kernel matrix or vector. The shape depends on the kernel's evaluation mode:

        * `full_covar`: `... x N x M`
        * `full_covar` with `last_dim_is_batch=True`: `... x K x N x M`
        * `diag`: `... x N`
        * `diag` with `last_dim_is_batch=True`: `... x K x N`
    """
    if last_dim_is_batch:
        x1 = x1.transpose(-1, -2).unsqueeze(-1)
        x2 = x2.transpose(-1, -2).unsqueeze(-1)

    x1_eq_x2 = torch.equal(x1, x2)
    res = None

    if diag:
        # Special case the diagonal because we can return all zeros most of the time.
        if x1_eq_x2:
            return torch.zeros(*x1.shape[:-2], x1.shape[-2], dtype=x1.dtype, device=x1.device)
        else:
            res = torch.linalg.norm(x1 - x2, dim=-1, ord=ord)
            return res.pow(ord)
    else:
        res = torch.cdist(x1, x2, p=ord).clamp_min(1e-15)
        return res.pow(ord)

gpplus.kernels.power_exponential_kernel.PowerExponentialKernelFixed ¤

Bases: UnconstrainedKernel

Source code in gpplus/kernels/power_exponential_kernel.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class PowerExponentialKernelFixed(UnconstrainedKernel):
    has_lengthscale = True  # Enable lengthscale functionality
    is_stationary = True  # The kernel is stationary

    def __init__(self, power=2.0, **kwargs):
        # Validate that power is between 1 and 2
        if not (1 <= power <= 2):
            raise ValueError("The 'power' parameter must be between 1 and 2.")
        # power is the exponent parameter (κ)
        super().__init__(**kwargs)
        self.power = power

    def forward(self, x1, x2, diag=False, **params):
        scaling_factors = torch.pow(10, self.lengthscale / self.power)

        x1_ = x1.mul(scaling_factors)
        x2_ = x2.mul(scaling_factors)

        return postprocess_(self.covar_dist(x1_, x2_, ord=self.power, diag=diag, **params))
has_lengthscale = True class-attribute instance-attribute ¤
is_stationary = True class-attribute instance-attribute ¤
power = power instance-attribute ¤
ard_num_dims = ard_num_dims instance-attribute ¤
eps = eps instance-attribute ¤
distance_module = None instance-attribute ¤
__pdist_supports_batch = True instance-attribute ¤
__init__(power=2.0, **kwargs) ¤
Source code in gpplus/kernels/power_exponential_kernel.py
16
17
18
19
20
21
22
def __init__(self, power=2.0, **kwargs):
    # Validate that power is between 1 and 2
    if not (1 <= power <= 2):
        raise ValueError("The 'power' parameter must be between 1 and 2.")
    # power is the exponent parameter (κ)
    super().__init__(**kwargs)
    self.power = power
forward(x1, x2, diag=False, **params) ¤
Source code in gpplus/kernels/power_exponential_kernel.py
24
25
26
27
28
29
30
def forward(self, x1, x2, diag=False, **params):
    scaling_factors = torch.pow(10, self.lengthscale / self.power)

    x1_ = x1.mul(scaling_factors)
    x2_ = x2.mul(scaling_factors)

    return postprocess_(self.covar_dist(x1_, x2_, ord=self.power, diag=diag, **params))
covar_dist(x1: Tensor, x2: Tensor, diag: bool = False, last_dim_is_batch: bool = False, ord: float = 2, **params) -> Tensor ¤

This is a helper method for computing the Euclidean distance between all pairs of points in :math:\mathbf x_1 and :math:\mathbf x_2.

:param x1: First set of data (... x N x D). :param x2: Second set of data (... x M x D). :param diag: Should the Kernel compute the whole kernel, or just the diag? If True, it must be the case that x1 == x2. (Default: False.) :param last_dim_is_batch: If True, treat the last dimension of x1 and x2 as another batch dimension. (Useful for additive structure over the dimensions). (Default: False.) :param square_dist: If True, returns the squared distance rather than the standard distance. (Default: False.) :return: The kernel matrix or vector. The shape depends on the kernel's evaluation mode:

* `full_covar`: `... x N x M`
* `full_covar` with `last_dim_is_batch=True`: `... x K x N x M`
* `diag`: `... x N`
* `diag` with `last_dim_is_batch=True`: `... x K x N`
Source code in gpplus/kernels/unconstrained_kernel.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def covar_dist(
    self,
    x1: Tensor,
    x2: Tensor,
    diag: bool = False,
    last_dim_is_batch: bool = False,
    # square_dist: bool = False,
    ord: float = 2,
    **params,
) -> Tensor:
    r"""
    This is a helper method for computing the Euclidean distance between
    all pairs of points in :math:`\mathbf x_1` and :math:`\mathbf x_2`.

    :param x1: First set of data (... x N x D).
    :param x2: Second set of data (... x M x D).
    :param diag: Should the Kernel compute the whole kernel, or just the diag?
        If True, it must be the case that `x1 == x2`. (Default: False.)
    :param last_dim_is_batch: If True, treat the last dimension
        of `x1` and `x2` as another batch dimension.
        (Useful for additive structure over the dimensions). (Default: False.)
    :param square_dist:
        If True, returns the squared distance rather than the standard distance. (Default: False.)
    :return: The kernel matrix or vector. The shape depends on the kernel's evaluation mode:

        * `full_covar`: `... x N x M`
        * `full_covar` with `last_dim_is_batch=True`: `... x K x N x M`
        * `diag`: `... x N`
        * `diag` with `last_dim_is_batch=True`: `... x K x N`
    """
    if last_dim_is_batch:
        x1 = x1.transpose(-1, -2).unsqueeze(-1)
        x2 = x2.transpose(-1, -2).unsqueeze(-1)

    x1_eq_x2 = torch.equal(x1, x2)
    res = None

    if diag:
        # Special case the diagonal because we can return all zeros most of the time.
        if x1_eq_x2:
            return torch.zeros(*x1.shape[:-2], x1.shape[-2], dtype=x1.dtype, device=x1.device)
        else:
            res = torch.linalg.norm(x1 - x2, dim=-1, ord=ord)
            return res.pow(ord)
    else:
        res = torch.cdist(x1, x2, p=ord).clamp_min(1e-15)
        return res.pow(ord)

gpplus.kernels.gaussian_kernel.GaussianKernel ¤

Bases: UnconstrainedKernel

Source code in gpplus/kernels/gaussian_kernel.py
11
12
13
14
15
16
17
18
19
20
21
22
23
class GaussianKernel(UnconstrainedKernel):
    has_lengthscale = True  # Enable lengthscale functionality
    is_stationary = True  # The kernel is stationary

    def forward(self, x1, x2, diag=False, **params):
        power = 2.0

        scaling_factors = torch.pow(10, self.lengthscale / power)

        x1_ = x1.mul(scaling_factors)
        x2_ = x2.mul(scaling_factors)

        return postprocess_gaussian(self.covar_dist(x1_, x2_, ord=power, diag=diag, **params))
has_lengthscale = True class-attribute instance-attribute ¤
is_stationary = True class-attribute instance-attribute ¤
ard_num_dims = ard_num_dims instance-attribute ¤
eps = eps instance-attribute ¤
distance_module = None instance-attribute ¤
__pdist_supports_batch = True instance-attribute ¤
forward(x1, x2, diag=False, **params) ¤
Source code in gpplus/kernels/gaussian_kernel.py
15
16
17
18
19
20
21
22
23
def forward(self, x1, x2, diag=False, **params):
    power = 2.0

    scaling_factors = torch.pow(10, self.lengthscale / power)

    x1_ = x1.mul(scaling_factors)
    x2_ = x2.mul(scaling_factors)

    return postprocess_gaussian(self.covar_dist(x1_, x2_, ord=power, diag=diag, **params))
__init__(ard_num_dims: Optional[int] = None, batch_shape: Optional[torch.Size] = None, active_dims: Optional[Tuple[int, ...]] = None, lengthscale_prior: Optional[Prior] = None, lengthscale_constraint: Optional[SoftClamp] = None, eps: float = 1e-06, **kwargs) ¤
Source code in gpplus/kernels/unconstrained_kernel.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def __init__(
    self,
    ard_num_dims: Optional[int] = None,
    batch_shape: Optional[torch.Size] = None,
    active_dims: Optional[Tuple[int, ...]] = None,
    lengthscale_prior: Optional[Prior] = None,
    lengthscale_constraint: Optional[SoftClamp] = None,
    eps: float = 1e-6,
    **kwargs,
):
    super(Kernel, self).__init__()  # Call Module's __init__ and Skip Kernel's __init__
    self._batch_shape = torch.Size([]) if batch_shape is None else batch_shape
    if active_dims is not None and not torch.is_tensor(active_dims):
        active_dims = torch.tensor(active_dims, dtype=torch.long)
    self.register_buffer("active_dims", active_dims)
    self.ard_num_dims = ard_num_dims

    self.eps = eps

    param_transform = kwargs.get("param_transform")

    if lengthscale_constraint is None:
        lengthscale_constraint = SoftClamp(lower_bound=-5, upper_bound=3, margin=1e-2)
        # lengthscale_constraint = gpytorch.constraints.Interval(lower_bound=-5, upper_bound=3)

    if param_transform is not None:
        # warnings.warn(
        #     "The 'param_transform' argument is now deprecated. If you want to use a different "
        #     "transformation, specify a different 'lengthscale_constraint' instead.",
        #     DeprecationWarning,
        # )
        warnings.warn(
            "The 'param_transform' argument is now deprecated.",
            DeprecationWarning,
        )

    if self.has_lengthscale:
        lengthscale_num_dims = 1 if ard_num_dims is None else ard_num_dims
        self.register_parameter(
            name="raw_lengthscale",
            parameter=torch.nn.Parameter(torch.zeros(*self.batch_shape, 1, lengthscale_num_dims)),
        )
        if lengthscale_prior is not None:
            if not isinstance(lengthscale_prior, Prior):
                raise TypeError("Expected gpytorch.priors.Prior but got " + type(lengthscale_prior).__name__)
            self.register_prior(
                "lengthscale_prior", lengthscale_prior, self._lengthscale_param, self._lengthscale_closure
            )
            # self.register_prior("lengthscale_prior", lengthscale_prior, "lengthscale")

        self.register_constraint("raw_lengthscale", lengthscale_constraint)

    self.distance_module = None
    # TODO: Remove this on next official PyTorch release.
    self.__pdist_supports_batch = True
covar_dist(x1: Tensor, x2: Tensor, diag: bool = False, last_dim_is_batch: bool = False, ord: float = 2, **params) -> Tensor ¤

This is a helper method for computing the Euclidean distance between all pairs of points in :math:\mathbf x_1 and :math:\mathbf x_2.

:param x1: First set of data (... x N x D). :param x2: Second set of data (... x M x D). :param diag: Should the Kernel compute the whole kernel, or just the diag? If True, it must be the case that x1 == x2. (Default: False.) :param last_dim_is_batch: If True, treat the last dimension of x1 and x2 as another batch dimension. (Useful for additive structure over the dimensions). (Default: False.) :param square_dist: If True, returns the squared distance rather than the standard distance. (Default: False.) :return: The kernel matrix or vector. The shape depends on the kernel's evaluation mode:

* `full_covar`: `... x N x M`
* `full_covar` with `last_dim_is_batch=True`: `... x K x N x M`
* `diag`: `... x N`
* `diag` with `last_dim_is_batch=True`: `... x K x N`
Source code in gpplus/kernels/unconstrained_kernel.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def covar_dist(
    self,
    x1: Tensor,
    x2: Tensor,
    diag: bool = False,
    last_dim_is_batch: bool = False,
    # square_dist: bool = False,
    ord: float = 2,
    **params,
) -> Tensor:
    r"""
    This is a helper method for computing the Euclidean distance between
    all pairs of points in :math:`\mathbf x_1` and :math:`\mathbf x_2`.

    :param x1: First set of data (... x N x D).
    :param x2: Second set of data (... x M x D).
    :param diag: Should the Kernel compute the whole kernel, or just the diag?
        If True, it must be the case that `x1 == x2`. (Default: False.)
    :param last_dim_is_batch: If True, treat the last dimension
        of `x1` and `x2` as another batch dimension.
        (Useful for additive structure over the dimensions). (Default: False.)
    :param square_dist:
        If True, returns the squared distance rather than the standard distance. (Default: False.)
    :return: The kernel matrix or vector. The shape depends on the kernel's evaluation mode:

        * `full_covar`: `... x N x M`
        * `full_covar` with `last_dim_is_batch=True`: `... x K x N x M`
        * `diag`: `... x N`
        * `diag` with `last_dim_is_batch=True`: `... x K x N`
    """
    if last_dim_is_batch:
        x1 = x1.transpose(-1, -2).unsqueeze(-1)
        x2 = x2.transpose(-1, -2).unsqueeze(-1)

    x1_eq_x2 = torch.equal(x1, x2)
    res = None

    if diag:
        # Special case the diagonal because we can return all zeros most of the time.
        if x1_eq_x2:
            return torch.zeros(*x1.shape[:-2], x1.shape[-2], dtype=x1.dtype, device=x1.device)
        else:
            res = torch.linalg.norm(x1 - x2, dim=-1, ord=ord)
            return res.pow(ord)
    else:
        res = torch.cdist(x1, x2, p=ord).clamp_min(1e-15)
        return res.pow(ord)