Skip to content
New
Latest News || 27 October 2026: Dr Soumava Mukherjee's invited talk at Queen's University Belfast joined device-level hardware innovation with channel-level control. || 22 October 2026: I received a Certificate of Appreciation for serving as a reviewer for IEEE IMAS 2026. || 15 October 2026: I presented a poster on beam-domain ML fingerprinting for RIS-aided mmWave localisation at the Centre for Wireless Innovation's annual symposium. || 15 October 2026: CWI's annual symposium brought research and industry perspectives on 6G, ISAC, optical wireless, AI, and future networks to Queen's University Belfast. || 14 October 2026: Erik Nordell of Ericsson visited our Keysight Lab for a live RIS-assisted video streaming demonstration.
Knowledge Hubmachine learning7. Ridge and Kernel Ridge Regression

machine learning learning note

7. Ridge and Kernel Ridge Regression

A beginner-friendly explanation of Ridge Regression and Kernel Ridge Regression from first principles, with intuition, equations, kernels, and Python examples.

At a glance

  • Regularization changes the fitted ruleRidge adds an L2 coefficient penalty. Scale features using training data and normally leave the intercept unpenalized.
  • A kernel defines a feature-space comparisonRBF similarity falls with squared distance; gamma controls locality, while lambda controls regularization.
  • Keep tuning inside cross-validationFit the scaler and model inside every training fold. Dense kernel methods also have a quadratic matrix-memory cost.

The Big Picture

Ridge Regression and Kernel Ridge Regression are both used for regression, which means they predict a number.

Examples:

  • Predict house price.
  • Predict temperature.
  • Predict received signal strength.
  • Predict localization error in meters.
  • Predict channel gain.

The important question is:

Given some input features, what numerical value should the model predict?

Ridge Regression starts from Linear Regression and makes it more stable. Kernel Ridge Regression starts from Ridge Regression and makes it able to learn curved, non-linear patterns.

References for this section3

Start from Linear Regression

Linear Regression assumes the output can be predicted by adding weighted input features.

For one feature:

y^=β0+β1x\widehat y=\beta_0+\beta_1x
  • y^\widehat y is the prediction
  • xx: input feature.
  • β1\beta _{1}: learned slope.
  • β0\beta _{0}: intercept.

For many features:

y^=β0+∑j=1pβjxj\widehat y=\beta_0+\sum_{j=1}^{p}\beta_jx_j
  • xjx_{j}: input feature j.
  • βj\beta _{j}: learned weight for feature j.
  • pp: number of features.
  • β0\beta _{0} is the intercept.

Where:

SymbolMeaning
ŷpredicted output
x₁, x₂, ..., xₚinput features
β₁, β₂, ..., βₚlearned coefficients or weights
β₀bias or intercept

For example, in house-price prediction:

price^=β0+β1area+β2bedrooms+β3distance\begin{aligned}\widehat{\mathrm{price}}={}&\beta_0+\beta_1\mathrm{area}\\&+\beta_2\mathrm{bedrooms}+\beta_3\mathrm{distance}\end{aligned}
  • price\mathrm{price} is the prediction; area, bedrooms, and distance are input features.
  • β1\beta _{1}: learned coefficient of the first feature.
  • β2\beta _{2}: learned coefficient of the second feature.
  • β3\beta _{3}: learned coefficient of the third feature.
  • β0\beta _{0} is the baseline price.

Training means finding the best weights so the predictions are close to the true values.

References for this section3

How Linear Regression Learns

The model makes predictions, compares them with the true values, and tries to reduce the error.

For ordinary Linear Regression, the most common objective is:

min⁡β0,β∑i(yi−y^i)2\min_{\beta_0,\beta}\sum_i(y_i-\widehat y_i)^2
  • yiy_{i}: measured target for sample i.
  • y^i\widehat y_i: model prediction for sample i.
  • ∑i\sum _{i} totals squared errors.

In words:

make the squared prediction errors as small as possible

This is called ordinary least squares.

References for this section3

The Problem with Ordinary Linear Regression

Linear Regression can become unstable when:

  • The dataset is small.
  • The dataset contains noise.
  • Some features are strongly correlated.
  • There are too many features compared with the number of samples.
  • The model tries too hard to fit every training point.

When this happens, the model may learn very large weights.

Large weights often mean:

small change in input -> large change in prediction

That can make the model sensitive, unstable, and poor on new data.

References for this section3

What Ridge Regression Adds

Ridge Regression adds a penalty for large weights.

Ordinary Linear Regression:

min⁡ prediction error\min\ \mathrm{prediction\ error}
  • Prediction error measures disagreement between measured and predicted values; ordinary least squares uses the squared-error sum above.

Ridge Regression:

min⁡[prediction error+weight penalty]\min\big[\mathrm{prediction\ error}+\mathrm{weight\ penalty}\big]
  • Prediction error rewards a good fit; weight penalty discourages large coefficients.

A common Ridge objective is:

min⁡β0,β[∑i(yi−y^i)2+λ∑j=1pβj2]\min_{\beta_0,\beta}\left[\sum_i(y_i-\widehat y_i)^2+\lambda\sum_{j=1}^p\beta_j^2\right]
  • yiy_{i}: measured target for sample i.
  • y^i\widehat y_i: model prediction for sample i.
  • βj\beta _{j} is feature weight j.
  • λ≥0\lambda ≥ 0 sets how strongly the squared weights are penalized; the intercept is normally excluded.

Where:

TermMeaning
Σᵢ(yᵢ − ŷᵢ)²prediction error
Σⱼβⱼ²weight-size penalty
λregularization strength, called alpha in scikit-learn

The penalty Σⱼβⱼ² is called an L2 penalty.

References for this section3

Simple Ridge Intuition

Imagine two models:

A:y^=2x1+x2+0.5x3\mathrm{A}:\quad\widehat y=2x_1+x_2+0.5x_3 B:y^=80x1−75x2+20x3\mathrm{B}:\quad\widehat y=80x_1-75x_2+20x_3
  • x1x_{1}: first input feature, shared by both example models.
  • x2x_{2}: second input feature, shared by both example models.
  • x3x_{3}: third input feature, shared by both example models.
  • y^\widehat y is the prediction; compare coefficient magnitude only after putting features on comparable scales.

Both might fit the training data, but Model B is risky because the weights are huge. Ridge prefers a model like A if both models make similar prediction errors.

So Ridge says:

fit the data, but do not let the weights become unnecessarily large
References for this section3

What Alpha Does

The alpha value controls how much Ridge cares about keeping weights small.

alpha valueBehavior
0Same as ordinary Linear Regression
SmallLight regularization
MediumGood balance between fit and stability
Very largeStrong shrinkage, possible underfitting

If alpha is too small, Ridge may still overfit. If alpha is too large, the model may become too simple.

Read this lab carefully: polynomial Ridge uses P=diag⁡(0,1,…,1)P=\operatorname{diag}(0,1,\ldots,1) so the intercept is unpenalized. The RBF lab fixes a training-mean baseline yˉ\bar y and solves for residual targets; prediction is yˉ+∑iαiK(x,xi)\bar y+\sum_i\alpha_i K(x,x_i). This baseline is not a jointly optimized intercept.

What do regularization and kernel similarity change?

1. Formula and symbols
y^(x)=∑j=0pβjxj\widehat y(x)=\sum_{j=0}^{p}\beta_jx^j
(XTX+λP)β=XTy,P=diag⁡(0,1,…,1)(X^TX+\lambda P)\beta=X^Ty,\quad P=\operatorname{diag}(0,1,\ldots,1)
MSE=1N∑i(y^i−yi)2\mathrm{MSE}=\frac1N\sum_i(\widehat y_i-y_i)^2
  • pp: degree
  • XX: polynomial design matrix
  • β\beta: learned coefficients
  • yy: training targets
  • λ\lambda: penalty
  • PP: excludes the intercept from that penalty
  • NN: Number of examples in the set being scored

MSE is computed separately on training and validation sets of size N.

● Train · ○ Validation · Solid: fit · Dashed: generating functionx = −1x = +1; y-axis ±1.575
Model family
2. Work with the current inputs
(XTX+1.00×10−2P)β=XTy,p=5(X^TX+1.00\times10^{-2}P)\beta=X^Ty,\quad p=5
MSEtrain=112∑i(y^i−yi)2=0.0262\mathrm{MSE}_{\rm train}=\frac1{12}\sum_i(\widehat y_i-y_i)^2=0.0262
MSEval=140∑j(y^j−yj)2=0.0711\mathrm{MSE}_{\rm val}=\frac1{40}\sum_j(\widehat y_j-y_j)^2=0.0711
3. Result
Training MSE0.0262
Validation MSE0.0711
Prediction at x = 0.50.991
Twelve training and forty distinct validation examples from sin(πx)+0.3x with deterministic independent Gaussian noise. Only training labels enter fitting; validation is for tuning, not a final test score. Polynomial powers use x in [−1,1]; P leaves the intercept unpenalized. Outside the Ridge lab, λ=10⁻⁶ is a small fixed penalty. RBF KRR uses a fixed training-mean baseline. Axes rescale to show unstable fits; this is not a statistical bias/variance decomposition.
References for this section3

Ridge Compared with Other Regressions

MethodMain ideaBest when
Linear RegressionFit a straight-line relationshipData is clean and mostly linear
Ridge RegressionLinear Regression with L2 regularizationFeatures are correlated or noisy
Lasso RegressionLinear Regression with L1 regularizationYou want feature selection
Elastic NetMixes Ridge and LassoYou want shrinkage and feature selection
Polynomial RegressionAdds powers like x^2 and x^3The trend is curved but still simple
SVRUses a margin-based regression tubeYou want a robust kernel method
Kernel Ridge RegressionRidge with kernelsThe relationship is smooth and non-linear

Ridge is still a linear model. It makes Linear Regression more stable, but it does not automatically learn complex curves unless the features already describe those curves.

References for this section3

Why Ridge Is Useful

Ridge is useful because it improves generalization.

Generalization means:

performing well on new data, not only on the training data

Ridge is a good first choice when:

  • You need a strong baseline.
  • You want interpretable coefficients.
  • Your features are correlated.
  • You have many features.
  • You suspect ordinary Linear Regression is overfitting.
References for this section3

But What If the Pattern Is Not Linear?

Linear and Ridge Regression both try to fit a linear relationship in the original feature space.

But many real patterns are not linear.

Example:

x increases -> y first increases, then decreases

A straight line cannot model that well.

One solution is to create new features manually:

original feature: x
new features: x, x^2, x^3

Then a linear model can fit a curve:

y^=β0+β1x+β2x2+β3x3\widehat y=\beta_0+\beta_1x+\beta_2x^2+\beta_3x^3
  • xx: original input feature.
  • x2x^2: squared input feature.
  • x3x^3: cubed input feature.
  • β1\beta _{1}: learned coefficient of the first feature.
  • β2\beta _{2}: learned coefficient of the second feature.
  • β3\beta _{3}: learned coefficient of the third feature.
  • β0\beta _{0}: intercept.

This works, but manually creating all possible useful features can become difficult.

This is where kernels help.

References for this section3

What Is a Kernel?

A kernel is a function that measures similarity between two data points.

Simple idea:

kernel(point A, point B) = how similar A and B are

For a valid real kernel, every Gram matrix is symmetric positive semidefinite. The nearby/high, faraway/low intuition applies to the RBF kernel below; a linear kernel is a dot product and can even be negative.

For example, an RBF kernel behaves like this:

nearby points   -> high similarity
faraway points  -> low similarity

So instead of only asking:

what are the feature values?

a kernel method asks:

how similar is this new point to the training points?
References for this section3

Why Do We Use Kernels?

We use kernels because they allow simple algorithms to learn non-linear patterns.

The powerful idea is:

non-linear pattern in original space
        can become
linear pattern in a richer feature space

But we do not want to manually build that richer feature space. A kernel lets the model behave as if it is using many extra transformed features without explicitly creating them.

This is called the kernel trick.

References for this section3

Kernel Trick in Plain Language

Suppose the original data has only two features:

x=[x1,x2]Tx=[x_1,x_2]^T
  • xx is the input vector containing two measured features, x₁ and x₂.

A richer feature space might include:

ϕ(x)=[x1,x2,x12,x22,x1x2,…]T\phi(x)=[x_1,x_2,x_1^2,x_2^2,x_1x_2,\ldots]^T
  • ϕ(x)\phi (x) maps input x to a richer feature vector; products and powers capture nonlinear relationships.

Manually calculating all of these can be expensive.

A kernel gives the model the effect of this richer comparison directly:

compare points in a richer space without explicitly building that space

That is why kernels are useful.

The kernel trick: lift points until a straight line works

1. Formula and symbols
ϕ(x)=(x, x2),k(x,z)=ϕ(x)⊤ϕ(z)=xz+x2z2\phi(x)=(x,\ x^2),\qquad k(x,z)=\phi(x)^\top\phi(z)=xz+x^2z^2
lifted rule: y^=1[x2≥c]⇔∣x∣≥c\text{lifted rule: }\widehat y=\mathbf1[x^2\ge c]\quad\Leftrightarrow\quad|x|\ge\sqrt c
  • xx: Original one-dimensional input
  • ϕ(x)\phi(x): Feature map: the point drawn in a richer space
  • k(x,z)k(x,z): Kernel: the dot product in that space, computed from x and z directly
  • cc: Height of the straight separating line in the lifted space

The kernel trick: an algorithm that only needs dot products can use k(x, z) and never build φ(x) explicitly, even when φ has very many (or infinitely many) dimensions.

−10100.51original input xheight = lift × x²x² = c△ |x| > 0.5 · ○ |x| < 0.5 · lift = 1.00
2. Work with the current inputs
ϕ(0.8)=(0.8, 0.64),ϕ(−0.7)=(−0.7, 0.49)\phi(0.8)=(0.8,\ 0.64),\quad\phi(-0.7)=(-0.7,\ 0.49)
ϕ(0.8)⊤ϕ(−0.7)=(0.8)(−0.7)+(0.64)(0.49)=−0.2464=k(0.8,−0.7)\phi(0.8)^\top\phi(-0.7)=(0.8)(-0.7)+(0.64)(0.49)=-0.2464=k(0.8,-0.7)
lifted cut x2≥0.25⇒∣x∣≥0.500, accuracy=1.000\text{lifted cut }x^2\ge0.25\Rightarrow|x|\ge0.500,\ \text{accuracy}=1.000
3. Result
Best single cut on the line80.0%
Horizontal line after lifting100.0%c = 0.25
Fifteen points on a line; triangles are far from zero (|x| > 0.5), circles are near zero. No single cut on the line separates them, because the triangles sit on both sides. Lift each point to height x²: now one horizontal line separates the classes perfectly. A kernel method finds that straight line in the lifted space while only ever computing k(x, z).
References for this section3

Common Kernels

KernelEquationIntuition
LinearK(x, z) = xᵀzOrdinary linear similarity
PolynomialK(x, z) = (xᵀz + c)ᵈCaptures polynomial curves
RBFK(x, z) = exp(−γ‖x − z‖²)Nearby points influence each other strongly
LaplacianK(x, z) = exp(−γ‖x − z‖)Similar to RBF, with a different distance shape

Where:

SymbolMeaning
xone data point
zanother data point
xᵀzdot product similarity
‖x − z‖distance between points
γcontrols how quickly similarity falls with distance
dpolynomial degree
References for this section3

How Kernel Ridge Regression Works

Kernel Ridge Regression combines two ideas:

Ridge Regression = control model complexity using regularization
Kernel method    = compare points through a similarity function

So Kernel Ridge Regression does this:

1. Measure similarity between training points using a kernel.
2. Learn how much each training point should influence predictions.
3. Regularize the solution so it does not overfit.
4. Predict a new value from similarities to the training data.

The prediction has this form:

y^(x∗)=∑i=1nαiK(x∗,xi)\widehat y(x_*)=\sum_{i=1}^{n}\alpha_iK(x_*,x_i)
  • x∗x_* is a new input and xᵢ training input i
  • KK measures their kernel similarity.
  • αi\alpha _{i} is sample i's learned influence; summing contributions gives prediction ŷ.

Where:

SymbolMeaning
x*new point to predict
x₁, x₂, ..., xₙtraining points
K(x*, xᵢ)similarity between the new point and training point i
αᵢlearned influence weight for training point i

The training solution can be written compactly as:

(K+λI)α=y(K+\lambda I)\alpha=y
  • KK is the training-pair kernel matrix
  • II is the identity matrix and λ is regularization strength.
  • yy is the target vector; solving the linear system yields the influence-weight vector α.

In simple words:

y^(x∗)=α1K(x∗,x1)+α2K(x∗,x2)+⋯+αnK(x∗,xn)\begin{aligned}\widehat y(x_*)={}&\alpha_1K(x_*,x_1)+\alpha_2K(x_*,x_2)\\&+\cdots+\alpha_nK(x_*,x_n)\end{aligned}
  • nn is training-sample count; each αᵢ scales similarity K(x*, xᵢ) to training input xᵢ.
References for this section3

How the Kernel Helps

Suppose the true pattern is curved.

Plain Ridge tries to fit:

y^=β0+βTx\widehat y=\beta_0+\beta^Tx
  • βTx\beta ^Tx is the weighted sum of feature vector x
  • β0\beta _{0} is the intercept and ŷ the prediction.

Kernel Ridge can fit:

y^(x∗)=∑i=1nαiK(x∗,xi)\widehat y(x_*)=\sum_{i=1}^{n}\alpha_iK(x_*,x_i)
  • K(x∗,xi)K(x_*,x_i) compares new input x* with training input xᵢ
  • αi\alpha _{i} is its learned weight.

For RBF kernels, similarity falls with distance. Learned coefficients can have either sign, so the prediction is not simply a normalized average of nearby targets. This combination can fit smooth nonlinear functions.

Kernel ridge regression is a sum of bumps

1. Formula and symbols
y^(x)=yˉ+∑i=1nαi K(x,xi),K(x,xi)=e−γ(x−xi)2\widehat y(x)=\bar y+\sum_{i=1}^{n}\alpha_i\,K(x,x_i),\qquad K(x,x_i)=e^{-\gamma(x-x_i)^2}
(K+λI)α=y−yˉ1(K+\lambda I)\alpha=y-\bar y\mathbf 1
  • xix_i: Training input i (12 of them)
  • αi\alpha_i: Learned weight of the bump centred on x_i
  • K(x,xi)K(x,x_i): RBF similarity: 1 at x = x_i, fading with distance
  • γ\gamma: Width control: larger γ means narrower bumps
  • λ\lambda: Regularisation: larger λ keeps the α small and the curve smooth
  • yˉ\bar y: Training-mean baseline

Every prediction is literally the baseline plus a weighted sum of bumps centred on the training points.

-202fit = baseline + Σ bumps−101input xindividual bumps αᵢK(x, xᵢ) (scale ±1.8)— fit● data- - ȳ
2. Work with the current inputs
y^(0.5)=0.082+1.331−0.663+0.636+…=1.115\widehat y(0.5)=0.082+1.331-0.663+0.636+\ldots=1.115
α6=−0.506,x6=−0.091,max⁡i∣αi∣=1.664\alpha_{6}=-0.506,\quad x_{6}=-0.091,\quad\max_i|\alpha_i|=1.664
3. Result
Training MSE0.0067
Validation MSE0.0883
Largest |αᵢ|1.66big weights mean wiggly fits
Bottom: one RBF bump per training point, scaled by its learned weight αᵢ (the selected bump is highlighted). Top: baseline plus all bumps added together gives the fitted curve. Narrow bumps (large γ) can chase every point; wide bumps blend neighbours. Increasing λ shrinks all weights, flattening the curve towards the baseline.
References for this section3

Kernel Ridge Regression vs. KNN Regression

Kernel Ridge Regression and K-Nearest Neighbors can feel similar because both use the training samples during prediction. A new point is compared with stored training points, and nearby or similar points strongly influence the output.

KNN regression predicts by averaging the target values of the nearest neighbors:

y^(x∗)=1k∑i∈Nk(x∗)yi\widehat y(x_*)=\frac1k\sum_{i\in\mathcal N_k(x_*)}y_i
  • kk is neighbor count
  • Nk(x∗)\mathcal N_k(x_*) is the selected neighbor set for new input x*.
  • yiy_{i} is each neighbor's target; averaging them produces ŷ(x*).

Kernel Ridge Regression predicts using kernel similarities and learned influence weights:

y^(x∗)=∑i=1nαiK(x∗,xi)\widehat y(x_*)=\sum_{i=1}^{n}\alpha_iK(x_*,x_i)
  • αi\alpha _{i} is the learned influence of training input xᵢ
  • KK compares it with new input x*.

They can perform similarly when:

  • The target function is smooth.
  • Nearby inputs usually have nearby output values.
  • Features are scaled properly.
  • The RBF kernel bandwidth and the KNN value of k create a similar neighborhood size.

For an RBF kernel:

K(x∗,xi)=exp⁡(−γ∥x∗−xi∥2)K(x_*,x_i)=\exp(-\gamma\lVert x_*-x_i\rVert^2)
  • ∥x∗−xi∥2\lVert x_*-x_i\rVert^2 is squared feature-space distance
  • γ>0\gamma > 0 controls how quickly similarity falls with distance.
  • exp⁡\exp is the exponential function
  • KK approaches 1 for identical inputs and 0 for distant ones.

Nearby points have high similarity, and faraway points have low similarity. This is close in spirit to KNN, where nearby points dominate and faraway points are ignored.

The difference is in how the influence is computed:

AspectKNN RegressionKernel Ridge Regression
Prediction ideaAverage nearby target valuesWeighted sum of kernel similarities
Neighbor behaviorUses only the k nearest pointsUsually uses all training points, but far points may have tiny kernel values
WeightsUsually equal for the selected neighborsLearned globally through α = (K + λI)⁻¹y
Training costAlmost no trainingMore expensive training because it solves a regularized kernel system
Prediction costCan be slow for large training setsAlso can be slow because prediction depends on training samples
SmoothnessCan be piecewise and jumpyUsually smoother with kernels such as RBF
RegularizationMainly controlled by kControlled by λ and kernel parameters such as γ

So the short intuition is:

KNN: nearby examples vote by their target values.
KRR: similar examples influence the prediction through a smooth, regularized kernel model.

Using training samples in either prediction formula is not data leakage. Fit preprocessing and the model using training observations. Validation may guide tuning, but those observations then cannot serve as an untouched final test. Comparing a test point with stored training inputs at prediction time is legitimate; using test labels or fitting on test observations contaminates final evaluation.

References for this section3

Ridge vs. Kernel Ridge Regression

QuestionRidge RegressionKernel Ridge Regression
Basic shapeLinearNon-linear with kernels
Prediction usesFeature weightsSimilarity to training points
Main equationŷ = β₀ + βᵀxŷ(x*) = ΣᵢαᵢK(x*, xᵢ)
Complexity controlL2 penalty on weightsRidge-style regularization on kernel solution
InterpretabilityHigherLower
Training costUsually lowerCan be high for large datasets
Prediction speedFastSlower when many training samples exist
Best useStable linear baselineSmooth non-linear pattern
References for this section3

Kernel Ridge vs. Support Vector Regression

Kernel Ridge Regression and Support Vector Regression can both use kernels, but they learn in different ways.

AspectKernel Ridge RegressionSupport Vector Regression
Main loss ideaPenalizes squared errorsIgnores small errors inside an epsilon tube
RegularizationControlled by alphaControlled by C
Kernel parametersExample: gamma for RBFExample: gamma for RBF
Prediction styleOften uses many training samplesOften uses fewer support vectors
Practical feelSmooth and conceptually simpleMore margin-based and robust

KRR can be easier to understand first because it is basically:

Ridge Regression + kernel similarity
References for this section3

Which One Should I Use?

SituationGood starting choice
Need a simple baselineLinear Regression
Linear model overfitsRidge Regression
Need feature selectionLasso Regression
Small dataset where local similarity is enoughKNN Regression
Data has smooth non-linear patternKernel Ridge Regression with RBF
Dataset is very largeRidge, Random Forest, Gradient Boosting, or neural models
Need very fast predictionRidge or another compact linear model
Need a strong tabular modelRandom Forest or Gradient Boosting

Start simple. Try Ridge first. If residual plots show curved patterns, then try Kernel Ridge.

References for this section3

Practical Checklist

  • Scale features before using Ridge or KRR.
  • Tune alpha with cross-validation.
  • For RBF KRR, tune both alpha and gamma.
  • Use ordinary Ridge as a baseline before KRR.
  • Use KRR carefully on large datasets because kernel matrices can become expensive.
  • Check residual plots to see whether the model is missing non-linear structure.
References for this section3

Python: Ridge Regression

The following examples share the built-in diabetes dataset and train/test split. Grid search wraps the entire scaler/model pipeline so preprocessing is refitted inside each training fold. Lock tuning decisions before inspecting final test scores.

from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

model = make_pipeline(
    StandardScaler(),
    Ridge(alpha=1.0)
)

model.fit(X_train, y_train)
pred = model.predict(X_test)

print("MAE:", round(mean_absolute_error(y_test, pred), 3))
print("R2:", round(r2_score(y_test, pred), 3))
References for this section3

Python: Tune Ridge Alpha

from sklearn.model_selection import GridSearchCV

ridge_cv = GridSearchCV(
    make_pipeline(StandardScaler(), Ridge()),
    param_grid={"ridge__alpha": [0.01, 0.1, 1.0, 10.0, 100.0]},
    scoring="neg_mean_absolute_error",
    cv=5,
)

ridge_cv.fit(X_train, y_train)
pred = ridge_cv.predict(X_test)

print("MAE:", round(mean_absolute_error(y_test, pred), 3))
print("R2:", round(r2_score(y_test, pred), 3))
References for this section3

Python: Kernel Ridge Regression

from sklearn.kernel_ridge import KernelRidge
from sklearn.model_selection import GridSearchCV

krr = GridSearchCV(
    make_pipeline(StandardScaler(), KernelRidge(kernel="rbf")),
    param_grid={
        "kernelridge__alpha": [0.01, 0.1, 1.0, 10.0],
        "kernelridge__gamma": [0.01, 0.1, 1.0],
    },
    scoring="neg_mean_absolute_error",
    cv=5,
)

krr.fit(X_train, y_train)
pred = krr.predict(X_test)

print("MAE:", round(mean_absolute_error(y_test, pred), 3))
print("R2:", round(r2_score(y_test, pred), 3))
References for this section3

Takeaway

Ridge Regression is Linear Regression with a stabilizing penalty. It is still linear, but it is often more reliable than ordinary Linear Regression when data is noisy or features are correlated.

Kernel Ridge Regression adds kernels, which let the model compare points by similarity and learn smooth non-linear patterns. The easiest way to remember it is:

Ridge Regression controls overfitting.
Kernels add non-linear similarity.
Kernel Ridge Regression combines both.

Continue with Classification, Regression and Compute Cost to build on this note.

References for this section3

Check your understanding

0 of 4 answered

  1. A squared-error sum is 10, weight squared-norm is 4 and λ=0.5. What is the Ridge objective?

  2. For RBF K(x,z)=exp(−γ‖x−z‖²), what is K(x,x)?

  3. What does increasing gamma do at a fixed nonzero distance?

  4. When using GridSearchCV, where should StandardScaler be fitted?

Complete references and further reading