Linear, ridge and lasso regression compared
Fit linear, ridge and lasso models, interpret their coefficients and residuals, and compare them by MAE and RMSE.
By Invicly Tech, , in AI and Machine Learning with Python. About 13 minutes to read.
In short
Linear regression predicts a number as a weighted sum of the features plus an intercept, choosing the weights that make the squared errors as small as possible. Ridge and lasso add a penalty on the size of the weights, which trades a little bias for more stable predictions; lasso can also push weights to exactly zero. You compare them on held-out data with MAE and RMSE, and you read the residuals to see where each one goes wrong.
Think of it like this: The penalty is like a budget for how strongly the model may react to each feature: ridge spreads the budget thinly, lasso spends it on a few features and gives the rest nothing.
Explained simply
Regression means predicting a number: a house price, a delivery time, next week's sales. Linear regression is the simplest way to do it. It gives every feature a weight, multiplies, adds everything up and adds a starting value called the intercept. Training means finding the weights that make the predictions as close as possible to the true values.
Close is measured by squared error. For each row you take the true value minus the prediction, square it and add all of those up. Ordinary least squares picks the weights that make that sum as small as it can be. Squaring means a big miss costs far more than a small one.
Plain linear regression can get jumpy when features are similar to each other, such as house size in square metres and number of rooms. Ridge and lasso calm it down by adding a penalty for large weights. Ridge shrinks every weight a little. Lasso can shrink some weights all the way to zero, which removes those features.
To judge the models you need two things. First, a baseline that just predicts the average, so you know what doing nothing clever scores. Second, error numbers on data the model never saw. MAE tells you the typical size of a miss. RMSE also counts the typical miss but gives extra weight to the big ones.
Press Play on a diagram to walk through it one step at a time.
- Minimises squared error only
- No penalty on weights
- Unstable when features are correlated
- Easy baseline to explain
- Adds alpha times the sum of squared weights
- Shrinks all weights towards zero
- Keeps every feature
- Good with many correlated features
- Adds alpha times the sum of absolute weights
- Sets some weights exactly to zero
- Acts as feature selection
- Can pick one of two correlated features at random
- 1Split
Hold out a test set before anything else
- 2Baseline
Predict the training mean or median
- 3Pipeline
StandardScaler then the linear model
- 4Tune alpha
Cross-validation on training data only
- 5Compare
MAE, RMSE and residual plots on the test set
- Few features, need a plain explanation
- Ordinary least squares
- Check residuals first
- Many correlated features
- Ridge
- Tune alpha with RidgeCV
- Suspect many useless features
- Lasso
- Tune alpha with LassoCV
- Check which weights hit zero
- Both problems at once
- ElasticNet
- Tune alpha and l1_ratio
In depth
What the penalty really does
Ridge minimises the squared error plus alpha times the sum of squared weights. Lasso uses alpha times the sum of absolute weights instead (scikit-learn also scales the error term for Lasso, so alpha values are not directly comparable between the two). When alpha is zero, both behave like ordinary least squares. As alpha grows, weights shrink and the model becomes simpler: training error rises a little, but the model reacts less to noise, so error on new data often falls.
The shape of the penalty explains the difference. The squared penalty grows slowly near zero, so ridge has little reason to make a weight exactly zero. The absolute-value penalty keeps pushing with the same force all the way down, so lasso drives small weights to zero. With two strongly correlated features, ridge tends to share the weight between them, while lasso often keeps one and drops the other.
- alpha = 0: same as ordinary least squares
- Larger alpha: smaller weights, simpler model
- RidgeCV and LassoCV pick alpha by cross-validation
- ElasticNet mixes both penalties with l1_ratio
Why scaling changes coefficients
A coefficient is measured in target units per feature unit. If you record distance in metres instead of kilometres, the coefficient for distance becomes a thousand times smaller, but the predictions of plain linear regression do not change at all. Ridge and lasso are different: their penalty only sees the size of the weight. A feature in small units needs a big weight, so it is penalised harder and shrinks more, purely because of the units you picked.
Standardising each feature to mean 0 and standard deviation 1 fixes this. After scaling, each coefficient means the change in prediction for one standard deviation of that feature, so you can compare sizes more fairly. Do the scaling inside a Pipeline so that the mean and standard deviation are learned from the training folds only.
- 1Training rows
Only these reach fit
- 2StandardScaler.fit
Learns mean and standard deviation
- 3Transform
Each feature now has mean 0, sd 1
- 4Model.fit
Penalty now treats features fairly
- 5Test rows
Transformed with the training statistics
Reading residual plots
A residual is the true value minus the prediction. Plot residuals against the predicted value. A healthy plot is a shapeless band around zero. A curve, such as residuals positive at both ends and negative in the middle, says the true relationship is not a straight line: try adding a squared term, a log transform or a non-linear model. A funnel that widens to the right says errors grow with the size of the target, which is common for prices and counts; modelling the log of the target often helps.
Also plot residuals against single features and against time if you have it. Errors that drift over time warn that the world is changing. A handful of huge residuals may be data errors, so look at those rows before you decide anything.
- Shapeless band around zero: fine
- Curve: missing non-linear structure
- Funnel: error grows with the target
- Drift over time: the data is changing
MAE, RMSE and which to report
MAE is the mean of the absolute errors. It is easy to explain: on average we are off by 12,000 euros. RMSE squares the errors, averages them and takes the square root, so it is in the same units but weighs large errors more heavily. RMSE is always at least as large as MAE. If RMSE is close to MAE, errors are fairly even; if it is much larger, a few rows have big misses.
Pick the metric that matches the cost. If a miss of 20 is twice as bad as a miss of 10, MAE fits. If big misses are disproportionately harmful, such as running out of stock, RMSE fits. Report both alongside the baseline so readers see the real improvement. R squared is popular but hides the scale of errors, so do not report it alone.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Fit ordinary least squares~35m
- 2Add ridge and lasso penalties~35m
- 3See why scaling changes coefficients~35m
- 4Read residual plots~35m
- 5Compare MAE and RMSE~35m
Key points
- Always compare against a naive baseline such as predicting the mean; a model that cannot beat it is not useful.
- Penalties depend on the scale of each feature, so scale features inside a pipeline before ridge or lasso.
- A coefficient means the change in the prediction for one unit of that feature with the others held fixed, in the units the model saw.
- MAE is the average size of an error; RMSE punishes large errors more, so RMSE much bigger than MAE signals a few big misses.
- Residual plots with curves or a funnel shape show the model is missing structure, not just noise.
Key terms
Tap a card to flip it. 0/6 known
Examples
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.metrics import mean_absolute_error, root_mean_squared_error
X, y = fetch_california_housing(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=42)
for m in [LinearRegression(), Ridge(alpha=1.0), Lasso(alpha=0.01)]:
pipe = make_pipeline(StandardScaler(), m).fit(X_tr, y_tr)
p = pipe.predict(X_te)
print(type(m).__name__, mean_absolute_error(y_te, p), root_mean_squared_error(y_te, p))root_mean_squared_error exists from scikit-learn 1.4. The dataset downloads once and is cached.
Comparing three models with cross-validation and a baseline
You have a housing table and want to know if regularisation helps. Step 1: split off a test set and leave it alone. Step 2: build a DummyRegressor that predicts the training mean. Step 3: build pipelines that scale and then fit LinearRegression, RidgeCV and LassoCV. Step 4: score each with 5-fold cross-validation on the training set, using negative MAE because scikit-learn scorers treat higher as better. Step 5: pick the winner, then report its MAE and RMSE once on the test set. Expect all three linear models to beat the dummy clearly and to sit close to each other on this dataset.
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression, RidgeCV, LassoCV
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
models = {"mean": DummyRegressor(),
"ols": make_pipeline(StandardScaler(), LinearRegression()),
"ridge": make_pipeline(StandardScaler(), RidgeCV(alphas=[0.1, 1, 10, 100])),
"lasso": make_pipeline(StandardScaler(), LassoCV(random_state=0))}
for name, m in models.items():
s = -cross_val_score(m, X_tr, y_tr, cv=5, scoring="neg_mean_absolute_error")
print(f"{name:6s} MAE {s.mean():.3f}")Reading coefficients and residuals from a fitted ridge model
After fitting, you want to explain the model. Step 1: pull the fitted Ridge step out of the pipeline and pair its coef_ with the feature names. Because the features were standardised, each value is the change in prediction for one standard deviation of that feature. Step 2: compute residuals on the test set. Step 3: plot residuals against predictions. If you see a funnel, try predicting the log of the target with TransformedTargetRegressor and compare MAE again.
import matplotlib.pyplot as plt
import pandas as pd
pipe = make_pipeline(StandardScaler(), Ridge(alpha=1.0)).fit(X_tr, y_tr)
coefs = pd.Series(pipe[-1].coef_, index=feature_names).sort_values()
print(coefs)
pred = pipe.predict(X_te)
resid = y_te - pred
plt.scatter(pred, resid, s=5, alpha=0.4)
plt.axhline(0, color="black")
plt.xlabel("predicted"); plt.ylabel("residual")
plt.show()Quick reference
- Always report a DummyRegressor baseline next to your model
- Ridge = L2 penalty, shrinks all weights; Lasso = L1 penalty, can zero weights
- Scale features inside a Pipeline before Ridge, Lasso or ElasticNet
- MAE = mean of absolute errors; RMSE = square root of mean squared error; RMSE >= MAE
- root_mean_squared_error is in sklearn.metrics from scikit-learn 1.4
- Use RidgeCV or LassoCV to choose alpha by cross-validation
- Funnel-shaped residuals: try modelling log(target)
Common mistakes
- Comparing raw coefficients across features measured in different units and calling the biggest one the most important.
- Fitting the scaler on all the data before splitting, which leaks test information into training.
- Picking alpha by looking at test-set scores instead of cross-validation on the training set.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Load the diabetes dataset from scikit-learn, split it 80/20 and compare a DummyRegressor with LinearRegression by MAE on the test set.
- Exercise 2medium
Fit Lasso with alpha values 0.01, 0.1, 1 and 10 on the scaled diabetes data and print how many coefficients are exactly zero for each.
- Exercise 3hard
On the California housing data, compare Ridge on the raw target with Ridge on log(target) using TransformedTargetRegressor. Report MAE and RMSE on the original scale for both.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is linear regression still worth learning when boosting models exist?
- Yes. It is fast, easy to explain and a strong baseline. If a complex model barely beats it, the simpler model is often the better choice.
- What is a good RMSE?
- There is no universal number, because RMSE is in the target's units. Compare it with a naive baseline and with what error the business can live with.
- Should I use ridge or lasso?
- Try both with cross-validation. Ridge is usually safer with many correlated features; lasso helps when you expect only a few features to matter and want a smaller model.
- Can I say a feature causes the target because its coefficient is large?
- No. A coefficient shows association given the other features in the model. Causal claims need experiments or careful causal methods.