# laplacekit_heteroscedastic

`laplacekit_heteroscedastic`

Heteroscedastic regression, with Gaussian likelihoods whose variance depends on the input.

End the model with `NaturalHead`, fit with `NaturalGaussian`, and split the predictive variance with `moments`:

``` python
lik = lk.heteroscedastic.NaturalGaussian()  # the model ends with NaturalHead()
post = lk.laplace(model, data, likelihood=lik, subset=lk.subsets.all, hessian_approx=lk.DenseGGN())
parts = lk.heteroscedastic.moments(lik, lk.predict_outputs(post, x_test))
parts.mean, parts.epistemic, parts.aleatoric
```

There are two likelihoods. In both, the model’s last axis holds two halves of $K$ entries each, for $K$ targets.

- `NaturalGaussian` follows Immer et al. 2023. The halves are the natural parameters $[\eta_1, \eta_2]$ of $K$ Gaussians, with $\eta_2 < 0$. This is laplace-torch’s `join_mean_variance` layout, with natural parameters in place of the mean and variance.
- `MeanVarianceGaussian` takes the halves as `[mean, var]`, and the Laplace approximation covers the mean only, as in laplace-torch’s `HeteroscedasticGaussianLikelihood`.

`moments` gives the predictive mean with its epistemic and aleatoric variances. `NoisyMean`, the default predictive of both likelihoods, is a Normal whose variance is the sum of the two.

`lk.marglik.train` does marginal-likelihood training, the other half of Immer et al., with either likelihood. The output Hessian of `NaturalGaussian` stays differentiable in $f$, and none of its checks run under vmap, so that training can use it.

Code reaches this package as `lk.heteroscedastic`, which imports it on first use.

## Classes

| Name | Description |
|----|----|
| [MeanVarianceGaussian](#laplacekit_heteroscedastic.MeanVarianceGaussian) | A Gaussian over targets `[..., K]` from outputs $f = [m, v]$, `[..., 2K]`. |
| [Moments](#laplacekit_heteroscedastic.Moments) | The predictive mean and its epistemic and aleatoric variances, each `[N, ..., K]`. |
| [NaturalGaussian](#laplacekit_heteroscedastic.NaturalGaussian) | A Gaussian over targets `[..., K]` in its natural parameters $f = [\eta_1, \eta_2]$. |
| [NaturalHead](#laplacekit_heteroscedastic.NaturalHead) | A last layer that maps $[h_1, h_2]$ to the natural parameters $[\eta_1, \eta_2]$. |
| [NoisyMean](#laplacekit_heteroscedastic.NoisyMean) | The default predictive of `NaturalGaussian` and `MeanVarianceGaussian`. |

### MeanVarianceGaussian

``` python
MeanVarianceGaussian(eps=1e-06)
```

A Gaussian over targets `[..., K]` from outputs $f = [m, v]$, `[..., 2K]`.

$m$ is the mean and $v$ the variance, clamped from below at $\epsilon$ to $\bar{v} = \max(v, \epsilon)$. For each target,

$$p(y \mid f) = \mathcal{N}(y \mid m, \bar{v}), \qquad
H = \operatorname{diag}(1 / \bar{v}, 0),$$

where $H$ is the output Hessian, $1 / \bar{v}$ on the mean and zero on the variance. `log_prob` detaches the variance, so the Laplace approximation covers the mean only, as in laplace-torch’s `HeteroscedasticGaussianLikelihood`.

The fitted parameters must include the head that outputs the mean. Use `subset=lk.subsets.all` or a subset that holds that head. `last_layer` takes only the head that runs last, and if that is the variance head, its curvature is zero.

The probe calls `check_outputs` (`HasOutputCheck`) on the first batch, with or without targets, so an odd last axis fails early. KFAC refuses this likelihood, so use `DiagGGN` or `DenseGGN`. The default predictive is `NoisyMean`.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| eps | float | The lower clamp $\epsilon$ on the variance, as in `nn.GaussianNLLLoss`. | `1e-06` |

#### Methods

| Name | Description |
|----|----|
| [average](#laplacekit_heteroscedastic.MeanVarianceGaussian.average) | A Normal from draws $f$, `[S, N, ..., 2K]`. |
| [check_outputs](#laplacekit_heteroscedastic.MeanVarianceGaussian.check_outputs) | Raise `StructureError` unless $f$ is `[N, ..., 2K]`. |
| [default_link](#laplacekit_heteroscedastic.MeanVarianceGaussian.default_link) | `NoisyMean`, on an exact or a sampled output covariance. |
| [distribution](#laplacekit_heteroscedastic.MeanVarianceGaussian.distribution) | A Normal with mean $m$ and variance $\bar{v}$. |
| [log_prob](#laplacekit_heteroscedastic.MeanVarianceGaussian.log_prob) | $\log \mathcal{N}(y \mid m, \bar{v})$ summed over the $K$ targets. |
| [output_hessian](#laplacekit_heteroscedastic.MeanVarianceGaussian.output_hessian) | The diagonal $H = \operatorname{diag}(1 / \bar{v}, 0)$. |

##### average

``` python
MeanVarianceGaussian.average(f, /)
```

A Normal from draws $f$, `[S, N, ..., 2K]`.

Its mean is the mean of the $m_s$. Its variance is the sample variance of the $m_s$ (divided by $S - 1$) plus the mean of the $\bar{v}_s$.

###### Parameters

| Name | Type   | Description                           | Default    |
|------|--------|---------------------------------------|------------|
| f    | Tensor | The drawn outputs, `[S, N, ..., 2K]`. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | Distribution | A `torch.distributions.Normal` over the targets, `[N, ..., K]`. |

###### Raises

| Name | Type           | Description               |
|------|----------------|---------------------------|
|      | StructureError | $f$ has an odd last axis. |

##### check_outputs

``` python
MeanVarianceGaussian.check_outputs(f, /)
```

Raise `StructureError` unless $f$ is `[N, ..., 2K]`.

###### Parameters

| Name | Type    | Description                           | Default    |
|------|---------|---------------------------------------|------------|
| f    | Outputs | The outputs $[m, v]$, `[N, ..., 2K]`. | *required* |

##### default_link

``` python
MeanVarianceGaussian.default_link(n_samples, /)
```

`NoisyMean`, on an exact or a sampled output covariance.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| n_samples | int \| Literal\['exact'\] | The number of Monte Carlo draws that `lk.predict` was given, or `None` for an exact output covariance. | *required* |

###### Returns

| Name | Type       | Description    |
|------|------------|----------------|
|      | LinkApprox | `NoisyMean()`. |

##### distribution

``` python
MeanVarianceGaussian.distribution(f, /)
```

A Normal with mean $m$ and variance $\bar{v}$.

###### Parameters

| Name | Type    | Description                           | Default    |
|------|---------|---------------------------------------|------------|
| f    | Outputs | The outputs $[m, v]$, `[N, ..., 2K]`. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | Distribution | A `torch.distributions.Normal` over the targets, `[N, ..., K]`. |

###### Raises

| Name | Type           | Description                                    |
|------|----------------|------------------------------------------------|
|      | StructureError | $f$ has fewer than 2 dims or an odd last axis. |

##### log_prob

``` python
MeanVarianceGaussian.log_prob(f, y, /)
```

$\log \mathcal{N}(y \mid m, \bar{v})$ summed over the $K$ targets.

$\bar{v}$ is detached. The result is shaped `f.shape[:-1]`.

###### Parameters

| Name | Type    | Description                           | Default    |
|------|---------|---------------------------------------|------------|
| f    | Outputs | The outputs $[m, v]$, `[N, ..., 2K]`. | *required* |
| y    | Targets | The targets, `[N, ..., K]`.           | *required* |

###### Returns

| Name | Type   | Description                                            |
|------|--------|--------------------------------------------------------|
|      | Tensor | The log-likelihood per example, shaped `f.shape[:-1]`. |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | $f$ has fewer than 2 dims or an odd last axis, or `y` is not `[..., K]`, shaped like $f$’s halves. |

##### output_hessian

``` python
MeanVarianceGaussian.output_hessian(f, /)
```

The diagonal $H = \operatorname{diag}(1 / \bar{v}, 0)$.

###### Parameters

| Name | Type    | Description                           | Default    |
|------|---------|---------------------------------------|------------|
| f    | Outputs | The outputs $[m, v]$, `[N, ..., 2K]`. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | OutputHessian | The output Hessian as an operator over vectors shaped like $f$. |

###### Raises

| Name | Type           | Description                                    |
|------|----------------|------------------------------------------------|
|      | StructureError | $f$ has fewer than 2 dims or an odd last axis. |

### Moments

``` python
Moments(mean, epistemic, aleatoric)
```

The predictive mean and its epistemic and aleatoric variances, each `[N, ..., K]`.

`moments` returns it. The total predictive variance is `epistemic + aleatoric`.

#### Parameters

| Name      | Type   | Description                             | Default    |
|-----------|--------|-----------------------------------------|------------|
| mean      | Tensor | The predictive mean.                    | *required* |
| epistemic | Tensor | The variance from the weight posterior. | *required* |
| aleatoric | Tensor | The noise variance of the likelihood.   | *required* |

### NaturalGaussian

``` python
NaturalGaussian()
```

A Gaussian over targets `[..., K]` in its natural parameters $f = [\eta_1, \eta_2]$.

$f$ is `[..., 2K]`. Per Gaussian,

$$\mu = -\frac{\eta_1}{2 \eta_2}, \qquad \sigma^2 = -\frac{1}{2 \eta_2}, \qquad
\log p(y \mid f) = \eta_1 y + \eta_2 y^2 - A(\eta) - \tfrac{1}{2} \log 2\pi,$$

with the log-partition $A(\eta) = -\eta_1^2 / (4 \eta_2) - \tfrac{1}{2} \log(-2 \eta_2)$. This needs $\eta_2 < 0$, which `NaturalHead` guarantees as the model’s last layer. The output Hessian is the Fisher $\nabla^2 A(\eta)$, which here equals the Hessian of $-\log p(y \mid f)$ at any $y$. On $(\eta_{1k}, \eta_{2k})$ it is the block

$$H_k = \begin{pmatrix} \sigma^2 & 2 \mu \sigma^2 \\
2 \mu \sigma^2 & 4 \mu^2 \sigma^2 + 2 \sigma^4 \end{pmatrix}.$$

The probe calls `check_outputs` (`HasOutputCheck`) on the first batch, with or without targets, so an odd last axis or an $\eta_2$ that is not negative fails early. The empirical Fisher differentiates `log_prob` and would get NaN otherwise.

KFAC refuses this likelihood, so use `DiagGGN` or `DenseGGN`. The default curvature never picks KFAC for it. The default predictive is `NoisyMean`, and `WeightSamples` averages its draws as a mixture.

#### Methods

| Name | Description |
|----|----|
| [average](#laplacekit_heteroscedastic.NaturalGaussian.average) | A Normal from draws $f$, `[S, N, ..., 2K]`. |
| [check_outputs](#laplacekit_heteroscedastic.NaturalGaussian.check_outputs) | Check that $f$ is `[N, ..., 2K]` with $\eta_2 < 0$. |
| [default_link](#laplacekit_heteroscedastic.NaturalGaussian.default_link) | `NoisyMean`, on an exact or a sampled output covariance. |
| [distribution](#laplacekit_heteroscedastic.NaturalGaussian.distribution) | A Normal with mean $\mu$ and variance $\sigma^2$. |
| [log_prob](#laplacekit_heteroscedastic.NaturalGaussian.log_prob) | $\log p(y \mid f)$ summed over the $K$ targets, shaped `f.shape[:-1]`. |
| [output_hessian](#laplacekit_heteroscedastic.NaturalGaussian.output_hessian) | The blocks $H_k = \nabla^2 A(\eta)$ on $(\eta_{1k}, \eta_{2k})$. |

##### average

``` python
NaturalGaussian.average(f, /)
```

A Normal from draws $f$, `[S, N, ..., 2K]`.

Its mean is the mean of the $\mu_s$. Its variance is the sample variance of the $\mu_s$ (divided by $S - 1$) plus the mean of the $\sigma^2_s$.

###### Parameters

| Name | Type   | Description                           | Default    |
|------|--------|---------------------------------------|------------|
| f    | Tensor | The drawn outputs, `[S, N, ..., 2K]`. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | Distribution | A `torch.distributions.Normal` over the targets, `[N, ..., K]`. |

###### Raises

| Name | Type           | Description                           |
|------|----------------|---------------------------------------|
|      | StructureError | $f$ has an odd last axis.             |
|      | ValueError     | An entry of $\eta_2$ is not negative. |

##### check_outputs

``` python
NaturalGaussian.check_outputs(f, /)
```

Check that $f$ is `[N, ..., 2K]` with $\eta_2 < 0$.

###### Parameters

| Name | Type    | Description                                     | Default    |
|------|---------|-------------------------------------------------|------------|
| f    | Outputs | The outputs $[\eta_1, \eta_2]$, `[N, ..., 2K]`. | *required* |

###### Raises

| Name | Type           | Description                                    |
|------|----------------|------------------------------------------------|
|      | StructureError | $f$ has fewer than 2 dims or an odd last axis. |
|      | ValueError     | An entry of $\eta_2$ is not negative.          |

##### default_link

``` python
NaturalGaussian.default_link(n_samples, /)
```

`NoisyMean`, on an exact or a sampled output covariance.

###### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| n_samples | int \| Literal\['exact'\] | The number of Monte Carlo draws that `lk.predict` was given, or `None` for an exact output covariance. | *required* |

###### Returns

| Name | Type       | Description    |
|------|------------|----------------|
|      | LinkApprox | `NoisyMean()`. |

##### distribution

``` python
NaturalGaussian.distribution(f, /)
```

A Normal with mean $\mu$ and variance $\sigma^2$.

###### Parameters

| Name | Type    | Description                                     | Default    |
|------|---------|-------------------------------------------------|------------|
| f    | Outputs | The outputs $[\eta_1, \eta_2]$, `[N, ..., 2K]`. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | Distribution | A `torch.distributions.Normal` over the targets, `[N, ..., K]`. |

###### Raises

| Name | Type           | Description                                    |
|------|----------------|------------------------------------------------|
|      | StructureError | $f$ has fewer than 2 dims or an odd last axis. |
|      | ValueError     | An entry of $\eta_2$ is not negative.          |

##### log_prob

``` python
NaturalGaussian.log_prob(f, y, /)
```

$\log p(y \mid f)$ summed over the $K$ targets, shaped `f.shape[:-1]`.

It does not check $\eta_2 < 0$, so that it works under `torch.func` transforms.

###### Parameters

| Name | Type    | Description                                     | Default    |
|------|---------|-------------------------------------------------|------------|
| f    | Outputs | The outputs $[\eta_1, \eta_2]$, `[N, ..., 2K]`. | *required* |
| y    | Targets | The targets, `[N, ..., K]`.                     | *required* |

###### Returns

| Name | Type   | Description                                            |
|------|--------|--------------------------------------------------------|
|      | Tensor | The log-likelihood per example, shaped `f.shape[:-1]`. |

###### Raises

| Name | Type | Description |
|----|----|----|
|  | StructureError | $f$ has fewer than 2 dims or an odd last axis, or `y` is not `[..., K]`, shaped like $f$’s halves. |

##### output_hessian

``` python
NaturalGaussian.output_hessian(f, /)
```

The blocks $H_k = \nabla^2 A(\eta)$ on $(\eta_{1k}, \eta_{2k})$.

It stays differentiable in $f$.

###### Parameters

| Name | Type    | Description                                     | Default    |
|------|---------|-------------------------------------------------|------------|
| f    | Outputs | The outputs $[\eta_1, \eta_2]$, `[N, ..., 2K]`. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | OutputHessian | The output Hessian as an operator over vectors shaped like $f$. |

###### Raises

| Name | Type           | Description                                    |
|------|----------------|------------------------------------------------|
|      | StructureError | $f$ has fewer than 2 dims or an odd last axis. |
|      | ValueError     | An entry of $\eta_2$ is not negative.          |

### NaturalHead

``` python
NaturalHead(link='exp')
```

A last layer that maps $[h_1, h_2]$ to the natural parameters $[\eta_1, \eta_2]$.

Use it to end a model for `NaturalGaussian`. The halves of $h$, `[N, ..., 2K]`, map to

$$\eta_1 = h_1, \qquad \eta_2 = -\tfrac{1}{2} \exp(h_2) \;\text{ or }\;
\eta_2 = -\tfrac{1}{2} \big(\operatorname{softplus}(h_2) + 10^{-8}\big),$$

so $\eta_2 < 0$. It has no parameters.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| link | Link | `"exp"`, as in Immer et al., or `"softplus"`. With `"softplus"`, $\eta_2$ stays negative in floating point even when $h_2$ is very negative. | `'exp'` |

#### Raises

| Name | Type       | Description                                 |
|------|------------|---------------------------------------------|
|      | ValueError | `link` is neither `"exp"` nor `"softplus"`. |

#### Methods

| Name | Description |
|----|----|
| [extra_repr](#laplacekit_heteroscedastic.NaturalHead.extra_repr) | Show the link in the module’s `repr`. |
| [forward](#laplacekit_heteroscedastic.NaturalHead.forward) | The natural parameters $[\eta_1, \eta_2]$. |

##### extra_repr

``` python
NaturalHead.extra_repr()
```

Show the link in the module’s `repr`.

###### Returns

| Name | Type | Description                 |
|------|------|-----------------------------|
|      | str  | For example `"link='exp'"`. |

##### forward

``` python
NaturalHead.forward(h)
```

The natural parameters $[\eta_1, \eta_2]$.

###### Parameters

| Name | Type   | Description                                  | Default    |
|------|--------|----------------------------------------------|------------|
| h    | Tensor | The previous layer’s output, `[N, ..., 2K]`. | *required* |

###### Returns

| Name | Type   | Description                          |
|------|--------|--------------------------------------|
|      | Tensor | $[\eta_1, \eta_2]$, shaped like `h`. |

###### Raises

| Name | Type           | Description                                    |
|------|----------------|------------------------------------------------|
|      | StructureError | `h` has fewer than 2 dims or an odd last axis. |

### NoisyMean

``` python
NoisyMean()
```

The default predictive of `NaturalGaussian` and `MeanVarianceGaussian`.

`lk.predict(post, x)` uses it for both likelihoods. It returns a Normal over the targets, with the mean from `moments` and the sum of its epistemic and aleatoric variances.

#### Methods

| Name | Description |
|----|----|
| [supports](#laplacekit_heteroscedastic.NoisyMean.supports) | True for a `NaturalGaussian` or a `MeanVarianceGaussian`. |

##### supports

``` python
NoisyMean.supports(lik, f_mu, /)
```

True for a `NaturalGaussian` or a `MeanVarianceGaussian`.

###### Parameters

| Name | Type       | Description                      | Default    |
|------|------------|----------------------------------|------------|
| lik  | Likelihood | The fit’s likelihood.            | *required* |
| f_mu | Tensor     | The output mean. It is not used. | *required* |

###### Returns

| Name | Type | Description |
|----|----|----|
|  | bool | Whether `lik` is a `NaturalGaussian` or a `MeanVarianceGaussian`. |

## Functions

| Name | Description |
|----|----|
| [moments](#laplacekit_heteroscedastic.moments) | Split the predictive into its mean, epistemic variance and aleatoric variance. |

### moments

``` python
moments(lik, out, /)
```

Split the predictive into its mean, epistemic variance and aleatoric variance.

For `NaturalGaussian`, the mean is $\mu(\hat\eta)$ and the aleatoric variance is $\sigma^2(\hat\eta)$, both at the output mean $\hat\eta$. The epistemic variance is

$$g^\top \Sigma_k \, g, \qquad g = \frac{\partial \mu}{\partial \eta}
= (\sigma^2, 2 \mu \sigma^2),$$

where $\Sigma_k$ is the $2 \times 2$ output covariance on $(\eta_{1k}, \eta_{2k})$, read from `out.cov.per_input()`. This is the same as linearizing $\mu(x; \theta)$ in $\theta$.

For `MeanVarianceGaussian`, the mean and the clamped variance come from the output mean, and the epistemic variance is the output variance of the mean.

#### Parameters

| Name | Type | Description | Default |
|----|----|----|----|
| lik | Likelihood | The fit’s likelihood, a `NaturalGaussian` or a `MeanVarianceGaussian`. | *required* |
| out | OutputGaussian | The linearized outputs, `lk.predict_outputs(post, x)`. `NaturalGaussian` allows at most `MAX_DENSE_EVENT` output entries per input. `MeanVarianceGaussian` reads only `out.cov.diagonal()`. | *required* |

#### Returns

| Name | Type    | Description    |
|------|---------|----------------|
|      | Moments | The `Moments`. |

#### Raises

| Name | Type | Description |
|----|----|----|
|  | CapabilityError | `lik` is neither a `NaturalGaussian` nor a `MeanVarianceGaussian`. |
|  | StructureError | The output mean has fewer than 2 dims or an odd last axis, or `out.cov.per_input()` refuses an input with too many output entries (as `SampleCov` does above `MAX_DENSE_EVENT`). |
|  | ValueError | With `NaturalGaussian`, an entry of $\eta_2$ at the output mean is not negative. |
