Skip to content

[BUG] BayesianRidge.predict with return_std=True fails to center test features, leading to incorrect predictive variance #33757

Closed

Description

@danilo-silva-ufsc

Describe the bug and give evidence about its user-facing impact

In BayesianRidge, the predictive variance calculation in the predict method is mathematically inconsistent with the training process when fit_intercept=True (the default). During fit(), the model centers the features (X - X_offset_), but during predict(), the variance is calculated using the raw test features X_test instead of centering them by the training mean X_offset_. As a result, the model reports its lowest uncertainty at the coordinate origin rather than at the center of the training data. For datasets far from the origin, this leads to significantly wrong uncertainty estimation, violating the principle that a Bayesian model should be most certain in the region where it has observed the most data.

Mathematical formulation

The original problem is $y = w^T x + b + \epsilon$. Instead, scikit-learn solves a centered version $y = w^T \tilde{x} + b' + \epsilon$, where $\tilde{x} = x - E[x]$, in order to find $w$ and $b'$, and finally $b$ is computed as $b = b' - w^T E[x]$. First, $b'$ is estimated using a frequentist approach (OLS/MLE) to be $b' = E[y]$, since $E[\tilde{x}] = 0$. This allows the problem to be reduced to $\tilde{y} = y - b' = w^T \tilde{x} + \epsilon$, on which a Bayesian approach is used to find $w$ (the posterior mean).

After $w$ is found, the predictive distribution of $\tilde{y}$ on a new test point $\tilde{x}$ is then given by
$$\tilde{\mu} = w^T \tilde{x}$$
$$\sigma^2 = \alpha^{-1} + \tilde{x}^T \Sigma_w \tilde{x}$$

But since $y = \tilde{y} + b'$, the predictive distribution of $y$ has the mean shifted to
$$\mu = w^T \tilde{x} + b'$$
while the variance stays the same.

However, our test point is actually $x$, so this all becomes
$$\mu = w^T (x - \mu_x) + b' = w^T x + b$$
$$\sigma^2 = \alpha^{-1} + (x - \mu_x)^T \Sigma_w (x - \mu_x)$$
where $\mu_x = E[x]$ (estimated using the training data).

Note that predict returns y_mean and y_std, where y_mean is exactly $\mu$, but y_std is not $\sigma$; instead it is
$$\alpha^{-1} + x^T \Sigma_w x$$

What is missing is to subtract $\mu_x$ from $x$ before the variance computation.

Steps/Code to Reproduce

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import BayesianRidge

n = 4

x_train = np.linspace(80, 100, n)
y_train = x_train + 10*np.random.RandomState(0).standard_normal(n)
model = BayesianRidge().fit(x_train.reshape(-1, 1), y_train)
x = np.linspace(-100, 100, 101)
y_mean, y_std = model.predict(x.reshape(-1, 1), return_std=True)
print(f"Std (x={x[50]:3g}): {y_std[50]:7.4f}")
print(f"Std (x={x[-1]:3g}): {y_std[-1]:7.4f}")
plt.plot(x_train, y_train, 'r.')
plt.plot(x, y_mean, 'b-')
plt.fill_between(x, y_mean - y_std, y_mean + y_std, color='RoyalBlue')
plt.title('Actual Results')
plt.show()

x_train = np.linspace(80, 100, n)
x_train -= x_train.mean()
y_train = x_train + 10*np.random.RandomState(0).standard_normal(n)
model = BayesianRidge().fit(x_train.reshape(-1, 1), y_train)
x = np.linspace(-100, 100, 101)
y_mean, y_std = model.predict(x.reshape(-1, 1), return_std=True)
print(f"Std (x={x[50]:3g}): {y_std[50]:7.4f}")
print(f"Std (x={x[-1]:3g}): {y_std[-1]:7.4f}")
plt.plot(x_train, y_train, 'r.')
plt.plot(x, y_mean, 'b-')
plt.fill_between(x, y_mean - y_std, y_mean + y_std, color='RoyalBlue')
plt.title('Correct when data is already centered')
plt.show()

x_train = np.linspace(80, 100, n)
y_train = x_train + 10*np.random.RandomState(0).standard_normal(n)
model = BayesianRidge().fit(x_train.reshape(-1, 1), y_train)
x = np.linspace(-100, 100, 101)
y_mean = model.predict(x.reshape(-1, 1))
_, y_std = model.predict((x - model.X_offset_).reshape(-1, 1), return_std=True)
print(f"Std (x={x[50]:3g}): {y_std[50]:7.4f}")
print(f"Std (x={x[-1]:3g}): {y_std[-1]:7.4f}")
plt.plot(x_train, y_train, 'r.')
plt.plot(x, y_mean, 'b-')
plt.fill_between(x, y_mean - y_std, y_mean + y_std, color='RoyalBlue')
plt.title('Expected Results')
plt.show()

Expected Results

Lowest variance close to the training data.
Image

Actual Results

Lowest variance close to the origin.
Image

Note that this is fine if the data is already centered; this is the problem scikit-learn is actually solving.
Image

Versions

System:
    python: 3.14.2 (main, Jan 27 2026, 23:59:57) [Clang 21.1.4 ]
executable: /home/danilo/sciml/.venv/bin/python
   machine: Linux-6.17.0-20-generic-x86_64-with-glibc2.42

Python dependencies:
      sklearn: 1.8.0
          pip: None
   setuptools: 81.0.0
        numpy: 2.4.2
        scipy: 1.17.0
       Cython: None
       pandas: 3.0.0
   matplotlib: 3.10.8
       joblib: 1.5.3
threadpoolctl: 3.6.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 24
         prefix: libscipy_openblas
       filepath: /home/danilo/sciml/.venv/lib/python3.14/site-packages/numpy.libs/libscipy_openblas64_-096271d3.so
        version: 0.3.31.dev
threading_layer: pthreads
   architecture: SkylakeX

       user_api: blas
   internal_api: openblas
    num_threads: 24
         prefix: libscipy_openblas
       filepath: /home/danilo/sciml/.venv/lib/python3.14/site-packages/scipy.libs/libscipy_openblas-6cdc3b4a.so
        version: 0.3.30
threading_layer: pthreads
   architecture: SkylakeX

       user_api: openmp
   internal_api: openmp
    num_threads: 24
         prefix: libgomp
       filepath: /home/danilo/sciml/.venv/lib/python3.14/site-packages/scikit_learn.libs/libgomp-e985bcbb.so.1.0.0
        version: None

Interest in fixing the bug

The bug is very easy to fix: just add a single line subtracting the mean before the variance calculation.

    def predict(self, X, return_std=False):
        y_mean = self._decision_function(X)
        if not return_std:
            return y_mean
        else:
            X = X - self.X_offset_  # <-- just add this line
            sigmas_squared_data = (np.dot(X, self.sigma_) * X).sum(axis=1)
            y_std = np.sqrt(sigmas_squared_data + (1.0 / self.alpha_))
            return y_mean, y_std

Activity

  1. amethystani commented on Apr 22, 2026

    @amethystani
  2. removed
    Needs Triage
    on Apr 29, 2026
  3. ogrisel commented on Apr 29, 2026

    @ogrisel
    Member

    Thanks for the report @danilo-silva-ufsc. Are you interested in opening a PR with the proposed fix yourself (along with a non-regression test and a changelog entry)?

    Or would you prefer someone else to work on this fix?

  4. XVX-016 commented on May 1, 2026

    @XVX-016

    I'd like to pick this up if that's okay

  5. danilo-silva-ufsc commented on May 1, 2026

    @danilo-silva-ufsc
    ContributorAuthor

    Sure @ogrisel , I have never a submitted a PR before but I will give it a try. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions