Regression in Machine Learning: Types, Metrics and Python Examples

Ask a model for a number instead of a label, and you’re doing regression. Regression in machine learning is supervised learning that predicts a continuous value, like a home price in dollars, from labeled examples. In scikit-learn, every regressor follows the same fit-then-predict pattern:

from sklearn.linear_model import LinearRegression

model = LinearRegression().fit(X_train, y_train)
predicted_prices = model.predict(X_test)

Here’s a request I get a lot: a team has past sales in a spreadsheet and wants an estimate for the next one. Someone draws an Excel trend line, and it’s off by six figures in pricey neighborhoods.

Quick answer: split the data into train and test sets, fit a plain linear model as a baseline, score it on the test set, then try a tree ensemble. On the housing data below, gradient boosting cut the average error from $53,320.01 to $31,105.52.

Every number here came from real runs on Python 3.12.5 with scikit-learn 1.9.1. The data is scikit-learn’s California housing set from the 1990 census, so prices are old but the workflow isn’t.

What is regression in machine learning?

Regression learns a function that maps input features to a numeric target. You give it rows where the answer is known, like past home sales, and it learns how each feature moves that number.

Because the answers are labeled, it’s a supervised method. That’s the main split from clustering and other unsupervised work; the statistical learning vs machine learning comparison explains where classic regression analysis fits in.

The other split is regression vs classification. Both are supervised, but they predict different kinds of output:

RegressionClassification
PredictsA number on a continuous scaleA category or class
ExampleSale price: $362,263.46Will the buyer default: yes/no
Typical metricsMAE, RMSE, R²Accuracy, precision, recall
scikit-learn classes*Regressor, LinearRegression*Classifier, LogisticRegression

Watch the name trap: logistic regression is a classifier. I cover it in scikit-learn logistic regression.

Which types of regression models should you know?

You don’t need twenty algorithms. These six cover nearly every regression job I’ve shipped, and the comparison below runs all of them:

ModelHow it worksWhen I reach for it
Linear regressionFits a straight line (or plane) by least squaresThe baseline, and whenever you must explain coefficients
Polynomial regressionAdds squared and interaction terms, then fits a linear modelCurved relationships with few features
RidgeLinear regression with an L2 penalty that shrinks coefficientsMany correlated features
LassoL1 penalty that can push coefficients to exactly zeroWhen you want built-in feature selection
Random forestAverages many decision trees trained on random samplesNon-linear data, little tuning time
Gradient boostingAdds trees one at a time, each fixing the last one’s errorsBest accuracy on tabular data

Linear regression with several inputs gets its own walk-through in multiple linear regression in Python, and curved fits like exponential or logistic growth curves are in non-linear regression with scikit-learn.

Load a real US housing dataset for regression

The California housing set has one row per census block group, with median income, house age, rooms, population, occupancy and location. scikit-learn downloads it once and caches it; if you still need the libraries, see Python libraries for machine learning.

from sklearn.datasets import fetch_california_housing

X, y = fetch_california_housing(return_X_y=True, as_frame=True)
y = y * 100_000          # target is in $100,000 units -> dollars

print(f"{X.shape[0]:,} block groups, {X.shape[1]} features")
print(f"Median home value: ${y.median():,.2f}")
print(f"Range: ${y.min():,.2f} to ${y.max():,.2f}")
print(f"Rows capped at the top value: {(y >= 500_000).sum()}")

Output:

20,640 block groups, 8 features
Median home value: $179,700.00
Range: $14,999.00 to $500,001.00
Rows capped at the top value: 992

That’s 20,640 rows and 8 features, with a median home value of $179,700.00. Notice the 992 rows sitting at $500,001.00: the census capped the top value, which matters later when you read the errors.

Train a linear regression model as a baseline

Start with the simplest model so you have something to beat. The split hides 20% of rows from training, so you can see whether the model generalizes:

from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split

X, y = fetch_california_housing(return_X_y=True, as_frame=True)
y = y * 100_000
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)

from sklearn.linear_model import LinearRegression
from sklearn.metrics import (mean_absolute_error,
                             root_mean_squared_error, r2_score)

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

print(f"Train rows: {len(X_train):,}  Test rows: {len(X_test):,}")
print(f"MAE:  ${mean_absolute_error(y_test, pred):,.2f}")
print(f"RMSE: ${root_mean_squared_error(y_test, pred):,.2f}")
print(f"R2:   {r2_score(y_test, pred):.3f}")
print(f"MedInc coefficient: ${model.coef_[0]:,.2f}")

Output:

Train rows: 16,512  Test rows: 4,128
MAE:  $53,320.01
RMSE: $74,558.14
R2:   0.576
MedInc coefficient: $44,867.49
VS Code output of a scikit-learn linear regression on California housing showing MAE, RMSE and R2 on the test set
The linear baseline misses by about $53,000 on average and explains a bit under 58% of the variance in home values.

The baseline trains on 16,512 rows and tests on 4,128. Its MAE is $53,320.01, RMSE is $74,558.14 and R² is 0.576. The MedInc coefficient says each extra $10,000 of median income adds about $44,867.49 to the predicted value, holding the other features fixed.

LinearRegression solves for those coefficients directly with least squares. Models like SGDRegressor get there iteratively instead, which is what gradient descent in scikit-learn walks through.

How do you measure a regression model’s accuracy?

Accuracy doesn’t work here: predicting $250,000.00 for a $251,000.00 home is neither right nor wrong. Regression uses error metrics:

MetricWhat it meansBaseline value
MAE (mean absolute error)Average size of a miss, in dollars$53,320.01
RMSE (root mean squared error)Like MAE, but big misses count extra$74,558.14
R² (coefficient of determination)Share of variance explained; 1.0 is perfect0.576

I report MAE to business people because it reads like money; a big gap between MAE and RMSE means a few large misses. If you came from classification, the scikit-learn accuracy score guide shows the metric that regression replaces.

Compare linear, polynomial, ridge, lasso, random forest and gradient boosting

Same split, same metrics, six models. Polynomial, ridge and lasso sit in a pipeline with StandardScaler, because penalties and squared terms behave badly when features use very different scales:

from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split

X, y = fetch_california_housing(return_X_y=True, as_frame=True)
y = y * 100_000
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.ensemble import (RandomForestRegressor,
                              HistGradientBoostingRegressor)
from sklearn.metrics import (mean_absolute_error,
                             root_mean_squared_error, r2_score)

models = {
    "Linear": LinearRegression(),
    "Polynomial": make_pipeline(StandardScaler(),
                                PolynomialFeatures(2), Ridge()),
    "Ridge": make_pipeline(StandardScaler(), Ridge(alpha=1.0)),
    "Lasso": make_pipeline(StandardScaler(), Lasso(alpha=100)),
    "Random forest": RandomForestRegressor(random_state=42, n_jobs=-1),
    "Gradient boosting": HistGradientBoostingRegressor(random_state=42),
}
for name, model in models.items():
    pred = model.fit(X_train, y_train).predict(X_test)
    mae = mean_absolute_error(y_test, pred)
    rmse = root_mean_squared_error(y_test, pred)
    r2 = r2_score(y_test, pred)
    print(f"{name:<18} MAE ${mae:>10,.2f}  RMSE ${rmse:>10,.2f}  R2 {r2:.3f}")

Output:

Linear             MAE $ 53,320.01  RMSE $ 74,558.14  R2 0.576
Polynomial         MAE $ 46,705.25  RMSE $ 68,021.52  R2 0.647
Ridge              MAE $ 53,319.31  RMSE $ 74,555.67  R2 0.576
Lasso              MAE $ 53,314.48  RMSE $ 74,464.18  R2 0.577
Random forest      MAE $ 32,798.67  RMSE $ 50,715.16  R2 0.804
Gradient boosting  MAE $ 31,105.52  RMSE $ 46,539.92  R2 0.835
VS Code output comparing six scikit-learn regression models on California housing with MAE, RMSE and R2
The two tree ensembles beat every linear variant by a wide margin, and gradient boosting comes out on top.

Ridge ($53,319.31 MAE) and lasso ($53,314.48) barely moved from plain linear regression. With 8 features and 16,512 rows, there’s little overfitting for a penalty to fix.

Polynomial terms helped: MAE fell to $46,705.25 and R² hit 0.647. The random forest reached 0.804, and HistGradientBoostingRegressor won with an MAE of $31,105.52 and R² of 0.835.

Pro Tip: on tabular data, I go straight from the linear baseline to HistGradientBoostingRegressor. It’s fast and handles missing values; neural networks rarely beat it here (see machine learning vs neural networks).

Plot predicted vs actual values from a regression model

Metrics give one number; a plot shows where it fails. Each dot is a test-set block group, and the red line marks perfect predictions. For quick charts, scatter plots from a pandas DataFrame work too:

from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split

X, y = fetch_california_housing(return_X_y=True, as_frame=True)
y = y * 100_000
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)

import matplotlib.pyplot as plt
from sklearn.ensemble import HistGradientBoostingRegressor

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

fig, ax = plt.subplots(figsize=(7, 5.5))
ax.scatter(y_test / 1000, pred / 1000, s=8, alpha=0.3)
ax.plot([0, 520], [0, 520], "r--", label="perfect prediction")
ax.set_xlabel("Actual median home value ($ thousands)")
ax.set_ylabel("Predicted value ($ thousands)")
ax.set_title("Gradient boosting: predicted vs actual (test set)")
ax.legend()
plt.tight_layout()
plt.show()
Matplotlib plot window of predicted vs actual California median home values from a scikit-learn gradient boosting regressor
Most points hug the red line, while the vertical stack at the right edge shows the homes capped at $500,001.

That right-edge column is the census cap. Those homes are worth more than $500,001, but the label can’t sa