05 / 15 · Bayesian Linear Models
The relevance vector machine
Give every weight its own prior precision, maximize the evidence, and most features switch themselves off: a sparse kernel model with error bars that competes with the support vector machine.
Bayesian linear regression · Support vector machines · Kernels
On this page 6
Fit a curve to 100 noisy points of , using a bias and one Gaussian bump centred on each point: 101 features. Bayesian linear regression puts one prior precision on all the weights and chooses it by the evidence. Every weight comes out nonzero, so each prediction sums all 100 bumps, much as kernel ridge regression does. A support vector regression is sparse in principle, yet on these data, with its constants and chosen by cross-validation, it keeps 95 of the 100 points as support vectors.
Now give every weight its own precision and maximize the evidence over all 101 of them. Most of the precisions run off to infinity, their weights are pinned at zero, and six bumps remain. The mechanism is called automatic relevance determination (ARD). On kernel features it gives the relevance vector machine (RVM) of Tipping (2001): a sparse kernel model that also reports a predictive variance and has no regularization constant to cross-validate.
Automatic relevance determination: one precision per weight#
The model is that of Bayesian linear regression: targets , a design matrix whose rows are the feature vectors , and Gaussian noise of precision . Only the prior changes. Each weight gets an independent Gaussian with a precision of its own:
where . The derivations of the posterior and of the evidence in the previous note never used the prior covariance being a multiple of . With in place of they give
where is the posterior of the weights and is the -th column of : the values of feature on all training inputs, not the feature vector of one input. The sum form of is written column by column, which a diagonal allows.
The sum form of , the covariance of the targets under the prior, shows what a precision does. Each feature adds to it. A small , a broad prior, lets the feature explain much variation along . With the term vanishes, the prior on is a point mass at zero, so is its posterior, and the feature is out of the model. Choosing the by the evidence therefore chooses which features to keep.
The idea comes from neural networks, where one precision per group of weights leaving an input lets the data decide which inputs are relevant (MacKay, 1994; Neal, 1996). Why a Gaussian prior should produce exact zeros is clearer one level up. If each had a gamma prior and were integrated out, the prior on would be a Student-, by the same gamma integral as the marginal of the mean: sharply peaked at zero, with heavy tails. With the hyperprior flat on a log scale, , the integral is (Tipping, 2001, Section 5.1). Like the Laplace prior behind the lasso, it puts much of its mass near zero and still allows a few large weights. The RVM maximizes over the instead of integrating them out, which keeps every step Gaussian.
Type-II maximum likelihood: MacKay’s fixed point#
The log evidence is the boxed formula of the previous note with replaced by and by . We differentiate it in one . The derivative through vanishes, as there, because maximizes the exponent. The log-determinant term gives, by fact 2 with , . So
Setting it to zero and multiplying by gives . The noise update is the one of the previous note, with in place of its ; since , this trace is . Together, the updates of MacKay (1992) used by Tipping (2001):
says how well the data determine weight . It lies in that range because , so and . When is large, the prior dominates, and . When is small, the data dominate and . If all the are equal, the add up to the effective number of parameters of the previous note: ARD counts it weight by weight.
Worked example. Take four points, two orthogonal features and , targets , a known , and both precisions starting at 1. Orthogonal columns make , so each weight is updated on its own:
| Quantity | Weight 1 | Weight 2 |
|---|---|---|
| after update 1 | ||
| after updates 2 and 3 | , |
The first feature is up to small noise, and its precision settles at once. The second only matches the noise. Its precision jumps by three orders of magnitude and keeps growing, by a factor that approaches per update (derived below), until it passes after 14 updates and is pruned.
Automatic relevance determination: one precision per weight
The algorithm alternates four steps, numbered as in the figure:
- compute and for the current and ;
- compute every ;
- compute the new and , and repeat until the precisions stop changing;
- remove every feature whose passes a large threshold, here : its weight is zero to machine precision, and removing it shrinks the matrices of step 1.
Why most precisions go to infinity#
The fixed point says where the precisions end up. It does not say why so many of them end at infinity. Start with two targets and one feature. The evidence is then a Gaussian over with covariance : a circle of noise, stretched along by . If points towards the observed , the stretch moves probability onto it. If is poorly aligned with , the stretch spreads the same unit of probability along a direction with no data, and the density at falls; the best is then infinite (Bishop, 2006, Section 7.2.2).
Faul and Tipping (2002) made this exact for any number of features, by looking at the evidence as a function of one with the others fixed. Split the covariance into the part without feature and its own term, , and define
The determinant lemma and Woodbury’s identity for a rank-one update, the case of the identities of the previous note, give
Substituting both into separates the dependence on :
The first term of is negative and rises to 0 as : it is the Occam penalty for the spread the feature adds to . The second is the gain in fit, largest for small . Differentiating,
If , the numerator is positive for every , increases all the way, and the best value is infinity. If , the numerator changes sign once, at the unique maximum:
Tipping and Faul (2003) call the sparsity and the quality of feature . measures how well the feature lines up with what the model without it leaves unexplained; measures how much of that model could already produce. A feature stays only if its quality, squared, beats its sparsity. In a kernel model with one bump per training point, neighbouring bumps are nearly the same vector. Once a few of them are in the model, the rest add little that is new: their falls below , and they are pruned.
In the worked example the features are orthogonal. Then with maps to , so acts on as multiplication by , and , :
The second feature fails the test, and the first one’s optimum is the value the iteration reached.
The evidence as a function of one precision
In the variables and the function is , one curve per , with its maximum at when . At a maximum of the evidence every coordinate is at its own optimum. The kept features therefore satisfy with , and the pruned ones ; the Code section checks both on the sinc data. The analysis also gives a much faster algorithm. Start from an empty model and repeatedly add, re-estimate or delete one feature, each time setting its to in closed form, so that the matrices never grow beyond the features in the model (Tipping and Faul, 2003).
Why MacKay’s update converges faster than EM#
The evidence can also be maximized by the EM algorithm, with the weights as the latent variable. The E-step is the posterior . The M-step maximizes the expected complete-data log-likelihood, the expectation of over that posterior:
Only the prior depends on , and with , setting gives . For , write with and . The cross term vanishes because , and for a fixed matrix , by the cyclic property of the trace:
Setting to zero,
The trace is the residual variance added by the posterior spread of the weights. Since , as for MacKay’s update above, a fixed point satisfies , which rearranges to MacKay’s . The two noise updates share their fixed points.
EM never decreases the evidence, because it is coordinate ascent on a lower bound that touches the evidence after each E-step. MacKay’s update has no such guarantee, yet Tipping found it much faster and never saw it take a downhill step (Tipping, 2001, Appendix A).
The sparsity and quality show why. With the other precisions fixed, and .
Derivation
The last section writes the posterior through : and . Their -th entries are and . The rank-one Woodbury identity for gives
Substituting, and .
Then , and the two updates of , and , become
Both have the fixed point . They differ for a feature that should leave, with . For large , MacKay’s update multiplies by about : a geometric climb. EM is , so it adds about : a linear climb. In the worked example the factor is and the step 256, so passes after 14 MacKay updates and after 3,906,246 EM updates. On the sinc data below, 5,000 EM iterations reach a log evidence of , against for MacKay’s 378, and have not pruned a single feature.
The RVM on kernel features, and the SVM#
With kernel features , so , the training inputs whose kernels survive are the relevance vectors. The RVM predicts with them alone:
with , and the features restricted to the kept ones. only defines a set of basis functions, so it does not have to be a positive semidefinite kernel: is a valid covariance for any , since .
| -insensitive SVR | RVM regression | |
|---|---|---|
| Sparse in | support vectors, on or outside the -tube | relevance vectors, with |
| Number of them | typically grows linearly with (Tipping, 2001, Section 1) | usually far fewer |
| Regularization | and by cross-validation | and by the evidence |
| Kernel | positive semidefinite | any basis functions |
| Output | a point estimate | a Gaussian predictive distribution |
| Training | a convex quadratic program | non-convex; per iteration, at the start |
Tipping’s own comparison uses 100 evenly spaced points of on and a linear-spline kernel (Tipping, 2001, Section 4.1). In the noise-free case the SVR has and the RVM a noise level fixed at ; in the noisy case the noise is uniform on and the SVR’s and come from 5-fold cross-validation.
| Sinc, 100 points | SVR | RVM |
|---|---|---|
| no noise: vectors kept | 36 | 9 |
| no noise: largest error | ||
| noise: vectors kept | 29 | 6 |
| noise: RMS deviation from the true function |
Worked example. Our own run is the one of the opening: the same 100 inputs, Gaussian noise of standard deviation , a bias and one Gaussian kernel per point. All 101 precisions start at 1, and is estimated too. The SVR uses the same kernel and picks and by 5-fold cross-validation from a grid of 16 pairs.
| RVM | SVR | |
|---|---|---|
| vectors kept | 6 of 101 features | 95 of 100 points |
| RMS distance from | ||
| settings | 378 iterations, noise level | , the smallest offered |
The six kernels sit at , , , , and , and the bias is pruned. At the optimum every kept feature has and every pruned one . One dataset and one grid do not rank the two methods; the contrast in the number of vectors is the typical one.
The relevance vector machine on the sinc function
Where it breaks#
The figure shows the weak point of the RVM’s error bars. Over the data the predictive standard deviation stays between and . At , far outside the data, it is , the noise level itself. The kept kernels are localized, so far from all of them , the term vanishes, and only is left. The model is as confident where it has no data as where it has the most (Rasmussen and Quiñonero-Candela, 2005). The prior over functions that the RVM implies is a degenerate Gaussian process, with six basis functions placed by the training inputs themselves (Rasmussen and Williams, 2006, Section 6.6); Gaussian processes with a stationary kernel do not have this flaw.
The other failures are of cost and of approximation. The evidence is not concave in the precisions: already along one coordinate, falls after its maximum towards the horizontal asymptote 0, and a concave function that starts to fall can never level off. So different starting values, pruning thresholds or stopping rules can end at different sets of relevance vectors. The first iterations invert an matrix, time and memory, which Tipping notes becomes impractical when the training examples number several thousand; the sequential algorithm avoids most of it. The evidence sets the and but not, in the basic algorithm, the width of the kernel, which is still cross-validated. And with one hyperparameter per weight, maximizing the evidence instead of integrating over the precisions is a cruder approximation than in the previous note. The exact zeros belong to that approximation: with proper gamma hyperpriors the precisions grow large but stay finite (Tipping, 2001, Section 2).
Redundant features are pruned, but an exact copy is not. If two columns are equal, , then by the sum form of the two terms and merge, depends only on , and the evidence cannot tell how the prior variance is split between the two weights. MacKay’s update does not choose either.
To see it, write the posterior through . Woodbury’s identity of fact 6, with as the middle matrix, and the push-through identity , checked by multiplying both sides by on the left and by on the right, give
With two equal columns, the entries for involve only and : and , so . MacKay’s update gives for both: the same factor, so their ratio never changes. In the Code section, precisions started at 1 and 2 end at and , and both features stay. A copy perturbed by noise of standard deviation is pruned within 20 updates.
What you should remember#
- ARD: prior , ; posterior and evidence as in Bayesian linear regression with for .
- MacKay’s update: , ; features with huge are pruned.
- One precision at a time: if , else ; redundant features fail the test.
- MacKay’s update drives a useless up geometrically, EM only linearly.
- RVM = ARD on kernel features: far fewer vectors than the SVM, error bars, any basis functions.
- Its error bars shrink to the noise level far from the data.
Code#
ARD by MacKay’s fixed point, the toy example and its and , the number of updates each rule needs to prune, the RVM on noisy sinc data with the sparsity condition checked at the optimum, EM on the same data, an SVR, and an exact copy of a feature that is never pruned. The script runs in about four seconds; exact numbers, and in rare cases the set of relevance vectors, can differ across platforms and library versions.
import numpy as np
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV
np.set_printoptions(suppress=True)
def rvm(Phi, t, rule='mackay', iters=5000, prune=1e9, tol=1e-6):
"""Type-II maximum likelihood with one precision per weight and an estimated noise precision.
rule='mackay' uses the fixed point, rule='em' the EM updates; weights whose precision passes `prune` are removed."""
n, m = Phi.shape
alpha, keep, b = np.ones(m), np.arange(m), 1 / np.var(t)
for it in range(1, iters + 1):
P = Phi[:, keep]
S = np.linalg.inv(np.diag(alpha[keep]) + b * P.T @ P) # posterior covariance of the kept weights
mu = b * S @ P.T @ t # posterior mean
gamma = 1 - alpha[keep] * np.diag(S) # how well each weight is determined
if rule == 'mackay':
new = gamma / mu ** 2
b = (n - gamma.sum()) / np.sum((t - P @ mu) ** 2)
else: # EM with w as the latent variable
new = 1 / (mu ** 2 + np.diag(S))
b = n / (np.sum((t - P @ mu) ** 2) + np.trace(P @ S @ P.T))
change = np.max(np.abs(np.log(new / alpha[keep])))
alpha[keep] = new
alpha[keep[new >= prune]] = np.inf # the weight is pinned at zero: prune it
keep = keep[new < prune]
if change < tol: break
P = Phi[:, keep]
S = np.linalg.inv(np.diag(alpha[keep]) + b * P.T @ P)
C = np.eye(n) / b + P @ np.diag(1 / alpha[keep]) @ P.T
logev = -0.5 * (n * np.log(2 * np.pi) + np.linalg.slogdet(C)[1] + t @ np.linalg.solve(C, t))
return keep, b * S @ P.T @ t, S, alpha, b, it, logev
# the toy: two orthogonal features, the noise precision beta = 100 known, alpha starts at (1, 1)
Phi = np.array([[1, 1], [1, -1], [2, -1], [2, 1.0]])
t = np.array([1.05, 0.92, 2.03, 2.02])
alpha = np.ones(2)
for k in range(1, 15):
S = np.linalg.inv(np.diag(alpha) + 100 * Phi.T @ Phi)
mu = 100 * S @ Phi.T @ t
gamma = 1 - alpha * np.diag(S)
alpha = gamma / mu ** 2
if k <= 3 or k == 14: print(k, mu.round(4), gamma.round(4), alpha.round(3).tolist())
# 1 [1.006 0.0299] [0.999 0.9975] [0.987, 1113.889]
# 2 [1.006 0.0079] [0.999 0.2642] [0.987, 4205.247]
# 3 [1.006 0.0026] [0.999 0.0869] [0.987, 12792.353]
# 14 [1.006 0. ] [0.999 0. ] [0.987, 1019386918.681]: alpha_2 passes 1e9 after 14 updates
s, q = 100 * (Phi ** 2).sum(axis=0), 100 * Phi.T @ t # for orthogonal features s_i = beta |phi_i|^2, q_i = beta phi_i . t
print(s, q, (q ** 2 / s).round(2), round(s[0] ** 2 / (q[0] ** 2 - s[0]), 4), round(alpha[0], 4))
# [1000. 400.] [1007. 12.] [1014.05 0.36] 0.9871 0.9871: q^2 > s for phi_1 only, and alpha_1 = s^2/(q^2 - s)
# the two updates of alpha_2 written in s and q: MacKay multiplies, EM adds
def updates_to_prune(update, a=1.0, k=0):
while a < 1e9: a, k = update(a), k + 1
return k
print(updates_to_prune(lambda a: s[1] * (a + s[1]) / q[1] ** 2), updates_to_prune(lambda a: (a + s[1]) ** 2 / (a + s[1] + q[1] ** 2)))
# 14 3906246
# 100 noisy points of sinc(x) = sin(x)/x, a bias and one Gaussian kernel of width 2 per point: m = 101 features
rng = np.random.default_rng(0)
x = np.linspace(-10, 10, 100)
sinc = lambda x: np.sinc(x / np.pi)
t = sinc(x) + 0.1 * rng.normal(size=100)
K = lambda a, b: np.exp(-(a[:, None] - b[None, :]) ** 2 / (2 * 2.0 ** 2))
feat = lambda z: np.hstack([np.ones((len(z), 1)), K(z, x)])
Phi = feat(x)
keep, mu, S, alpha, beta, it, logev = rvm(Phi, t)
xg = np.linspace(-10, 10, 1000)
Pg = feat(xg)[:, keep]
print(it, len(keep), 0 in keep, x[keep - 1].round(2), round(1 / np.sqrt(beta), 4)) # 378 6 False [-5.96 -3.13 -0.71 5.15 8.18 10. ] 0.0902
print(round(np.sqrt(np.mean((Pg @ mu - sinc(xg)) ** 2)), 4)) # 0.0403: RMS distance to the true sinc on a fine grid
sd = lambda P: np.sqrt(1 / beta + np.einsum('ij,jk,ik->i', P, S, P))
print(sd(Pg).min().round(4), sd(Pg).max().round(4), sd(feat(np.array([15.0]))[:, keep]).round(4)) # 0.0903 0.0993 [0.0903]: as confident at x = 15 as anywhere
# the sparsity condition at the optimum: q_i^2 > s_i exactly for the kept features, alpha_i = s_i^2/(q_i^2 - s_i)
C = np.eye(100) / beta + Phi[:, keep] @ np.diag(1 / alpha[keep]) @ Phi[:, keep].T
r, ok = [], True
for i in range(101):
phi = Phi[:, i]
Cm = C - np.outer(phi, phi) / alpha[i] if i in keep else C # C without feature i
s_i, q_i = phi @ np.linalg.solve(Cm, phi), phi @ np.linalg.solve(Cm, t)
r.append(q_i ** 2 / s_i)
if i in keep: ok &= bool(np.isclose(alpha[i], s_i ** 2 / (q_i ** 2 - s_i), rtol=1e-3))
r = np.array(r)
print(bool(np.all(r[keep] > 1)), bool(np.all(np.delete(r, keep) <= 1 + 1e-6)), ok, np.delete(r, keep).max().round(3)) # True True True 0.944
# EM on the same data: almost the same evidence after 5000 iterations, and nothing pruned yet
keep_em, *_, it_em, logev_em = rvm(Phi, t, rule='em')
print(round(logev, 3), it_em, len(keep_em), round(logev_em, 3)) # 81.954 5000 101 81.944
# a support vector regression with the same kernel, C and epsilon chosen by 5-fold cross-validation
svr = GridSearchCV(SVR(kernel='rbf', gamma=1 / (2 * 2.0 ** 2)), {'C': [0.1, 1, 10, 100], 'epsilon': [0.01, 0.05, 0.1, 0.2]}, cv=5).fit(x[:, None], t)
best = svr.best_estimator_
print(svr.best_params_, len(best.support_), round(np.sqrt(np.mean((best.predict(xg[:, None]) - sinc(xg)) ** 2)), 4))
# {'C': 1, 'epsilon': 0.01} 95 0.0497: 95 of the 100 points are support vectors
# an exact copy of a feature is never pruned: MacKay's update multiplies both precisions by the same factor
rng = np.random.default_rng(1)
f1, f2 = rng.normal(size=50), rng.normal(size=50)
t = f1 + 0.5 * f2 + 0.3 * rng.normal(size=50) # noise precision beta = 1 / 0.09, known
for eps in (0.0, 0.05):
Phi = np.column_stack([f1, f1 + eps * rng.normal(size=50), f2]) # the second column copies the first, exactly or with noise
alpha = np.array([1.0, 2.0, 1.0])
for _ in range(3000):
k = alpha < 1e9
S = np.linalg.inv(np.diag(alpha[k]) + Phi[:, k].T @ Phi[:, k] / 0.09)
mu = S @ Phi[:, k].T @ t / 0.09
alpha[k] = (1 - alpha[k] * np.diag(S)) / mu ** 2
print(eps, np.where(alpha < 1e9, alpha, np.inf).round(2))
# 0.0 [1.66 3.32 3.88]: both copies kept, precisions still in the ratio 1 : 2
# 0.05 [1.11 inf 3.88]: the noisy copy is pruned
Next#
The RVM’s evidence was available in closed form because the likelihood was Gaussian. For classification it is not: the targets are 0 or 1, the likelihood is a product of sigmoids, and neither the posterior over the weights nor the evidence has a formula. The next note replaces the posterior by a Gaussian centred at its mode, with the curvature there as its precision. This Laplace approximation gives Bayesian logistic regression, its moderated predictions, and the classification version of the RVM.
References#
- D. P. Vetrov, D. A. Kropotov. Байесовские методы машинного обучения, lecture course, Moscow State University, 2015. Course page; lecture 4, the relevance vector machine (slides).
- Конспект курса «Байесовские методы в анализе данных», 2026, github.com/bmml-team/bmml_ftda, лекция 2.
- M. E. Tipping. Sparse Bayesian Learning and the Relevance Vector Machine. Journal of Machine Learning Research, 1, 211–244, 2001. Sections 1 (the growth of the number of support vectors), 2 (the model and the updates), 4.1 (the sinc examples), 5.1 (the Student- prior), Appendix A (the EM and fixed-point updates).
- A. C. Faul, M. E. Tipping. Analysis of Sparse Bayesian Learning. Advances in Neural Information Processing Systems 14, 2002.
- M. E. Tipping, A. C. Faul. Fast Marginal Likelihood Maximisation for Sparse Bayesian Models. AISTATS, 2003.
- D. J. C. MacKay. Bayesian Interpolation. Neural Computation, 4(3), 415–447, 1992.
- D. J. C. MacKay. Bayesian Methods for Backpropagation Networks. In E. Domany, J. L. van Hemmen, K. Schulten (eds.), Models of Neural Networks III, Chapter 6, 211–254, Springer, 1994.
- R. M. Neal. Bayesian Learning for Neural Networks. Lecture Notes in Statistics 118, Springer, 1996.
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 7.2 (relevance vector machines; 7.2.2, the analysis of sparsity) and Section 9.3.4 (EM for the evidence).
- C. E. Rasmussen, J. Quiñonero-Candela. Healing the Relevance Vector Machine through Augmentation. ICML, 689–696, 2005.
- C. E. Rasmussen, C. K. I. Williams. Gaussian Processes for Machine Learning. MIT Press, 2006. Section 6.6 (relevance vector machines as degenerate Gaussian processes).