Machine Learning-Regression: Core Concepts and Operations

  1. Least Squares: Fit the model parameters by minimizing the sum of squared residuals.
  2. Regularization: Reduce model complexity by limiting parameter size, Ridge uses L2, Lasso uses L1.
  3. Nonlinear Regression: Polynomial Features and Kernel Methods can describe nonlinear relationships.
  4. Regression Metrics: Use indicators such as MAE, RMSE, R² to evaluate prediction errors from different perspectives.
  5. Generalization: Determine the model's predictive ability on new data through independent test sets, cross-validation and residual analysis.

1. Regression: Basic concept of regression

The regression model learns the relationship between the input feature XX and the continuous target variable yy:

y^=f(X;θ)\hat y=f(X;\theta)

Among them:

  • XX: Input feature (Features).
  • yy: True target value (Target).
  • y^\hat y: model prediction value.
  • θ\theta: model parameters.
  • e=y−y^e=y-\hat y: residual (Residual).

The training goal is usually to find suitable parameters so that the predicted value is as close to the true value as possible.

Common regression types

TypeFeatures
Linear RegressionFit the data using a linear relationship
Ridge RegressionAdd L2 regularization to linear regression
Lasso RegressionAdd L1 regularization to linear regression
Polynomial RegressionFitting nonlinear relationships using polynomial features
Support Vector RegressionRegression using margin and kernel functions
Tree-based RegressionUse decision trees and ensemble models to fit nonlinear relationships

This article mainly discusses the first five categories. Tree ensemble models such as Random Forest, Gradient Boosting, XGBoost can be placed in the Ensemble Learning article.

2. Linear Regression: linear regression

Linear regression assumes that the predicted value is a linear combination of input features.

For multiple features:

y^=w1x1+w2x2+⋯+wpxp+b\hat y=w_1x_1+w_2x_2+\cdots+w_px_p+b

Among them:

  • wiw_i: Characteristic coefficient.
  • bb: intercept (Intercept).
  • pp: Number of features.

Ordinary Least Squares(OLS)

Ordinary least squares estimates model parameters by minimizing the sum of squared residuals:

min⁡w,b∑i=1n(yi−y^i)2\min_{w,b}\sum_{i=1}^{n}(y_i-\hat y_i)^2

Squared error imposes a higher penalty on larger residuals.

The intuitive goal of linear regression is to find a straight line, or a hyperplane in a high-dimensional space, so that the sum of square distances from the observation point to the predicted result is as small as possible.

scikit-learn implementation

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

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

model = LinearRegression()
model.fit(X_train, y_train)

y_pred = model.predict(X_test)

View model parameters:

model.coef_       # regression coefficient
model.intercept_  # intercept
model.score(X_test, y_test)  # R²

Coefficient explanation

Assume we get:

Price^=5000+200Area−100Age\widehat{Price}=5000+200Area-100Age

can be interpreted as:

  • An increase in area by one unit, holding other variables constant, predicts a price increase of 200.
  • As the age of the house increases by one year, the predicted price decreases by 100 when other variables are held constant.

However, the regression coefficient reflects the statistical relationship in the model, and cannot be directly interpreted as the causal relationship.

Limitations of Linear Regression

  • Only linear combinations of features can be represented unless additional nonlinear features are constructed.
  • More sensitive to outliers.
  • When features are highly correlated, the coefficients may be unstable.
  • Extrapolating beyond the range of the training data may produce unreasonable predictions.

In addition, two concepts need to be distinguished:

  • linear regression is used to predict: the focus is on test set error and generalization ability.
  • Linear regression is used for statistical inference: It is also necessary to discuss coefficient significance, confidence intervals, error assumptions, etc.

scikit-learn is mainly for the former; the latter can usually use statsmodels.

3. Regularization: Regularization

Ordinary linear regression may appear:

  • Too many features.
  • The model is overfitting.
  • There is strong multicollinearity between features (Multicollinearity).
  • The model coefficient is too large or unstable.

Regularization (Regularization) controls model complexity by adding penalties to model parameters in the loss function.

Basic idea:

Loss=Prediction Error+λ⋅PenaltyLoss=Prediction\ Error+\lambda\cdot Penalty

where λ\lambda controls the regularization strength.

  • Weaker regularization: allows the model to fit the training data more freely.
  • Strong regularization: limiting parameter size may reduce model variance but increase bias.

Ridge Regression: L2 regularization

Ridge adds a coefficient sum-of-squares penalty to the ordinary least squares objective:

min⁡w,b[∑i(yi−y^i)2+α∑jwj2]\min_{w,b}\left[\sum_i(y_i-\hat y_i)^2+\alpha\sum_jw_j^2\right]

Its features:

  • Shrinks the coefficients towards 0.
  • Usually you don't compress coefficients directly to 0.
  • It can alleviate coefficient instability caused by multicollinearity.
  • Suitable for situations where multiple related features jointly participate in prediction.
from sklearn.linear_model import Ridge

model = Ridge(alpha=1.0)

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

Commonly used parameters:

  • alpha: Regularization strength.
  • fit_intercept: Whether to learn the intercept.
  • solver: Select numerical solution algorithm.

Generally, the larger alpha is, the more obvious the coefficient shrinkage is.

Lasso Regression: L1 regularization

Lasso uses the sum of the absolute values of the coefficients as a penalty:

min⁡w,b[12n∑i(yi−y^i)2+α∑j∣wj∣]\min_{w,b}\left[\frac{1}{2n}\sum_i(y_i-\hat y_i)^2+\alpha\sum_j|w_j|\right]

Its features:

  • Some coefficients can be compressed to exactly 0.
  • It has certain automatic feature selection effect.
  • Suitable for scenarios where some features may not be important.
  • When features are highly correlated, the selected features may be unstable.
from sklearn.linear_model import Lasso

model = Lasso(
    alpha=0.1,
    max_iter=10000,
)

model.fit(X_train, y_train)

print(model.coef_)

When a certain coef_ is 0, it means that the corresponding feature is excluded from the model.

Note: The loss functions of Ridge and Lasso in scikit-learn have different normalization conventions, so alpha with the same value cannot be directly regarded as the same intensity of punishment.

ElasticNet:L1 + L2

ElasticNet combines Ridge and Lasso:

Loss=12nRSS+α[ρ∥w∥1+1−ρ2∥w∥22]Loss=\frac{1}{2n}RSS+\alpha\left[\rho\|w\|_1+\frac{1-\rho}{2}\|w\|_2^2\right]
from sklearn.linear_model import ElasticNet

model = ElasticNet(
    alpha=0.1,
    l1_ratio=0.5,
)
  • alpha: Overall regularization strength.
  • l1_ratio: The relative ratio of L1 to L2.

ElasticNet tends to be more stable for highly correlated features than pure Lasso.

Comparison of the three

modelregularizationFeature selectionCommon uses
LinearRegressionNoneNolinear baseline model
RidgeL2Usually noMore relevant features
LassoL1YesSparse models, feature selection
ElasticNetL1 + L2YesBalancing sparsity and stability

When using a regularized linear model, the numerical features should usually be normalized first. Otherwise the units and scales of different features will affect the penalty effect.

4. Polynomial Regression: Polynomial regression

Linear regression can only directly represent linear combinations of input features.

But many real data have non-linear relationships, such as:

y=ax2+bx+cy=ax^2+bx+c

Polynomial regression transforms the original input into polynomial form by constructing new features.

For example:

x→[x,x2,x3]x\rightarrow[x,x^2,x^3]

Fitting can still be done using linear regression afterwards.

PolynomialFeatures

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline

model = make_pipeline(
    PolynomialFeatures(
        degree=2,
        include_bias=False,
    ),
    LinearRegression(),
)

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

degree=2 means generating polynomial features up to quadratic.

Suppose there are two features:

X=[x1,x2]X=[x_1,x_2]

Quadratic polynomials can generate:

[x1,x2,x12,x1x2,x22][x_1,x_2,x_1^2,x_1x_2,x_2^2]

Why is it still called linear regression?

Because although the model behaves nonlinearly to the input variables, it is still linear to the estimated parameters:

y^=w1x+w2x2+b\hat y=w_1x+w_2x^2+b

Degree and overfitting

  • Degree Too low: Complex relationships may not be fit.
  • Degree is too high: noise may be fitted and overfitting may occur.
  • Polynomial expansion of multiple features may cause the number of features to grow rapidly.

Therefore, it is necessary to select the appropriate Degree through cross-validation.

Combined with Ridge

When there are many polynomial features, regularization can be added:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge

model = make_pipeline(
    PolynomialFeatures(degree=3, include_bias=False),
    StandardScaler(),
    Ridge(alpha=1.0),
)

This combination is often more stable than simply raising Degree.

5. SVR:Support Vector Regression

Support Vector Regression (Support Vector Regression) is an application of a support vector machine (SVM) for regression tasks.

Unlike ordinary least squares regression, SVR introduces ε-insensitive Loss (ε-insensitive loss).

Its core idea is:

Construct a tolerance interval with width 2ϵ2\epsilon near the prediction function.

  • The error is within the tolerance interval: no ε-insensitive loss occurs.
  • Error exceeds the interval: Penalize the excess part.

Common loss functions:

Lϵ(y,y^)=max⁡(0,∣y−y^∣−ϵ)L_\epsilon(y,\hat y)=\max(0,|y-\hat y|-\epsilon)

scikit-learn implementation

from sklearn.svm import SVR
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

model = make_pipeline(
    StandardScaler(),
    SVR(
        kernel="rbf",
        C=1.0,
        epsilon=0.1,
    ),
)

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

Key hyperparameters

parametersfunction
kernelKernel function type
CControlling penalties for violating the ε tolerance interval
epsilonThe width of the insensitive area
gammaThe influence scale of kernel functions such as RBF

C

  • Larger C: Pay more attention to training error, which may increase the risk of overfitting.
  • Smaller C: allows larger training errors and generally constrains the model more strongly.

epsilon

  • Larger epsilon: tolerates more small errors and generally results in a simpler model.
  • Smaller epsilon: Requires the model to fit the data more precisely.

kernel

Common kernel functions:

SVR(kernel="linear")
SVR(kernel="poly")
SVR(kernel="rbf")

RBF Kernel:

K(xi,xj)=exp⁡(−γ∥xi−xj∥2)K(x_i,x_j)=\exp(-\gamma\|x_i-x_j\|^2)

RBF can model nonlinear relationships without explicitly generating high-dimensional polynomial features.

Advantages and Disadvantages of SVR

Advantages:

  • Supports nonlinear fitting.
  • Model complexity can be adjusted through C, epsilon, gamma.
  • It performs well on some small and medium-sized data sets.

Limitations:

  • More sensitive to feature scale.
  • Parameter selection has a greater impact on the effect.
  • Kernel SVR can be computationally expensive on large data sets.
  • The interpretability is generally weaker than linear models.

For larger data sets, consider LinearSVR or other models that are more suitable for large-scale data.

6. Regression Metrics: regression indicator

The regression model cannot only look at the training error, but needs to measure the predictive ability on an independent validation set or test set.

Most commonly used indicators:

indicatorNameoptimal direction
MAEMean Absolute ErrorThe smaller the better
MSEMean Squared ErrorThe smaller the better
RMSERoot Mean Squared ErrorThe smaller the better
R²Coefficient of DeterminationThe closer to 1 the better
MAPEMean Absolute Percentage ErrorThe smaller the better
MedAEMedian Absolute ErrorThe smaller the better

MAE: mean absolute error

MAE=1n∑i∣yi−y^i∣MAE=\frac{1}{n}\sum_i|y_i-\hat y_i|

Features:

  • The units are consistent with the target variable.
  • Easy to explain.
  • Compared to MSE, the penalty for extreme errors is weaker.

For example, MAE is 100, which means the average absolute prediction error is 100 target units.

MSE: mean square error

MSE=1n∑i(yi−y^i)2MSE=\frac{1}{n}\sum_i(y_i-\hat y_i)^2

Features:

  • Sensitive to large errors.
  • Objective function commonly used in model training.
  • The units are the square of the target variable's units, which is less intuitive than MAE.

RMSE: root mean square error

RMSE=1n∑i(yi−y^i)2RMSE=\sqrt{\frac{1}{n}\sum_i(y_i-\hat y_i)^2}

RMSE is the square root of MSE.

Features:

  • Same units as the original target variable.
  • Greater emphasis is placed on larger prediction errors.
  • Suitable for scenarios where large errors are costly.

R²: coefficient of determination

R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2R^2=1-\frac{\sum_i(y_i-\hat y_i)^2}{\sum_i(y_i-\bar y)^2}

where yˉ\bar y is the mean of the true values in the evaluation data.

Usually:

  • (R2=1)(R^2=1): The prediction was absolutely correct.
  • (R2=0)(R^2=0): Same as directly predicting the squared error of the evaluation set mean.
  • (R2<0)(R^2<0): Worse than this mean baseline.

R² is not the prediction accuracy, nor can it be simply interpreted as “what percentage of predictions are correct”.

For special data sets with constant target values, the definition and implementation of R² also require special treatment.

MAPE: Mean absolute percentage error

MAPE=1n∑i∣yi−y^iyi∣MAPE=\frac{1}{n}\sum_i\left|\frac{y_i-\hat y_i}{y_i}\right|

Commonly used for relative error analysis of sales volume, demand, etc.

But when the true value is 0 or very close to 0, MAPE may produce extremely large error values, so it needs to be used with caution.

scikit-learn implementation

from sklearn.metrics import (
    mean_absolute_error,
    mean_squared_error,
    root_mean_squared_error,
    mean_absolute_percentage_error,
    median_absolute_error,
    r2_score,
)

mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = root_mean_squared_error(y_test, y_pred)
mape = mean_absolute_percentage_error(y_test, y_pred)
medae = median_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

How to choose indicators?

  • MAE: Want to visually measure the average prediction deviation.
  • RMSE: Larger prediction errors are more costly.
  • R²: Measures the explanatory or predictive ability of the model relative to the mean baseline.
  • MAPE: Care about the relative error, and the true value will not be close to 0.
  • MedAE: Want to use an error statistic that is less sensitive to extreme values.

Real projects often report MAE, RMSE, and R² simultaneously, rather than looking at a single metric.

7. Residual Analysis: Residual analysis

In addition to Metrics, the structure of model prediction errors should also be examined.

Residuals:

ei=yi−y^ie_i=y_i-\hat y_i

Common analysis:

  1. Whether the actual value is close to the predicted value.
  2. Is there an obvious trend in the residuals?
  3. Whether the residuals expand as the predicted value increases.
  4. Are there extreme outliers?
  5. Whether the model has systematic deviations in different data intervals.

Actual vs Predicted

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.scatter(y_test, y_pred, alpha=0.5)

lower = min(y_test.min(), y_pred.min())
upper = max(y_test.max(), y_pred.max())

ax.plot(
    [lower, upper],
    [lower, upper],
    "--",
    color="red",
)

ax.set(
    xlabel="Actual",
    ylabel="Predicted",
    title="Actual vs Predicted",
)

plt.show()

Ideally, the predicted value should be as close to the diagonal as possible.

Residual Plot

residuals = y_test - y_pred

fig, ax = plt.subplots()

ax.scatter(y_pred, residuals, alpha=0.5)
ax.axhline(0, linestyle="--", color="red")

ax.set(
    xlabel="Predicted",
    ylabel="Residual",
    title="Residual Plot",
)

plt.show()

If the residuals are significantly curved, it may mean that non-linear relationships are missed.

If the dispersion of the residuals changes significantly with the predicted values, heteroskedasticity (Heteroscedasticity) may exist.

Note: Residual analysis is a diagnostic tool and there is no guarantee that a model or data problem can be identified from a single graph.

8. Cross-validation and parameter selection

K-Fold Cross-validation

Cross-validation reduces the reliance of model evaluation on a single partition of the data.

from sklearn.model_selection import cross_val_score
from sklearn.linear_model import Ridge

model = Ridge(alpha=1.0)

scores = cross_val_score(
    model,
    X_train,
    y_train,
    cv=5,
    scoring="neg_root_mean_squared_error",
)

rmse_scores = -scores

print(rmse_scores.mean())
print(rmse_scores.std())

The scoring form of many error indicators in scikit-learn uses negative values because its scoring interface follows the convention of "the bigger the better".

RidgeCV / LassoCV

For regularization parameters alpha, scikit-learn provides built-in cross-validation models:

import numpy as np
from sklearn.linear_model import RidgeCV, LassoCV

ridge = RidgeCV(
    alphas=np.logspace(-3, 3, 20),
    cv=5,
)

lasso = LassoCV(
    cv=5,
    random_state=42,
    max_iter=10000,
)

After training you can view:

ridge.alpha_
lasso.alpha_

If normalization is involved, both normalization and parameter search should be included in the training fold to avoid Data Leakage.

GridSearchCV

For example SVR:

from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR

pipeline = Pipeline([
    ("scaler", StandardScaler()),
    ("svr", SVR(kernel="rbf")),
])

param_grid = {
    "svr__C": [0.1, 1, 10, 100],
    "svr__epsilon": [0.01, 0.1, 0.5],
    "svr__gamma": ["scale", 0.01, 0.1],
}

search = GridSearchCV(
    pipeline,
    param_grid,
    cv=5,
    scoring="neg_root_mean_squared_error",
    n_jobs=-1,
)

search.fit(X_train, y_train)

print(search.best_params_)

The test set should be retained until the model and hyperparameters are basically determined before being used for final evaluation.

9. Complete Example: Comparing Different Regression Models

The following is a comparison of the prediction performance of several regression models by simulating nonlinear regression data.

import numpy as np
import pandas as pd

from sklearn.datasets import make_friedman1
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import (
    PolynomialFeatures,
    StandardScaler,
)
from sklearn.linear_model import (
    LinearRegression,
    Ridge,
    Lasso,
)
from sklearn.svm import SVR
from sklearn.metrics import (
    mean_absolute_error,
    root_mean_squared_error,
    r2_score,
)

# 1. Generate regression data
X, y = make_friedman1(
    n_samples=1000,
    n_features=5,
    noise=1.0,
    random_state=42,
)

# 2. Split training set and test set
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42,
)

# 3. Define model
models = {
    "Linear": LinearRegression(),

    "Ridge": make_pipeline(
        StandardScaler(),
        Ridge(alpha=1.0),
    ),

    "Lasso": make_pipeline(
        StandardScaler(),
        Lasso(alpha=0.01, max_iter=10000),
    ),

    "Polynomial": make_pipeline(
        PolynomialFeatures(
            degree=2,
            include_bias=False,
        ),
        StandardScaler(),
        Ridge(alpha=1.0),
    ),

    "SVR": make_pipeline(
        StandardScaler(),
        SVR(kernel="rbf", C=10, epsilon=0.1),
    ),
}

# 4. training and evaluation
results = []

for name, model in models.items():
    model.fit(X_train, y_train)

    y_pred = model.predict(X_test)

    results.append({
        "model": name,
        "MAE": mean_absolute_error(y_test, y_pred),
        "RMSE": root_mean_squared_error(y_test, y_pred),
        "R2": r2_score(y_test, y_pred),
    })

# 5. Compare models
results_df = pd.DataFrame(results)

print(results_df.sort_values("RMSE"))

The parameters here are only demonstration values and cannot be directly used as the optimal parameters in real projects.

Real projects should first use cross-validation to tune parameters, and then use an independent test set to evaluate the final model.

10. How to choose a regression algorithm?

algorithmAdvantageslimitationsRecommended scenarios
Linear RegressionSimple, explainable, fast to trainDifficult to directly fit complex nonlinearitiesBaseline model, linear relationship
RidgeAlleviating collinearity and making coefficients more stableMost features are not automatically removedMultiple related features
LassoSparse coefficient, feature selectionMay be unstable to related featuresHigh-dimensional, sparse features
Polynomial RegressionNonlinearities can be fitted explicitlyHigh-order features are prone to expansion and overfittingLow-dimensional, smoother nonlinearity
SVRSupports kernel methods and nonlinear fittingParameter adjustment is sensitive and large-scale training is expensiveSmall and medium-sized nonlinear data

It is recommended to use the following during actual development:

Dataset
   ↓
Linear Regression Baseline
   ↓
Ridge / Lasso
   ↓
Polynomial Features / SVR
   ↓
Cross-validation
   ↓
Model Comparison
   ↓
Residual Analysis
   ↓
Final Evaluation

The order here is not mandatory, but a modeling idea from simple to complex.

For larger tabular data, tree models such as Random Forest and Gradient Boosting are also candidate models worthy of comparison, but they can be discussed in the Ensemble Learning topic.

11. FAQ

1. Is feature standardization necessary?

uncertain.

  • Linear Regression: Common OLS Normalization is not usually mandatory.
  • Ridge/Lasso: Normalization is generally recommended.
  • SVR: Standardization is generally recommended.
  • Polynomial Regression: Polynomial features may have very different scales and often require appropriate scaling.

2. Does a high R² mean the model is reliable?

uncertain.

Still need to confirm:

  • Test whether the data is independent.
  • Whether Data Leakage occurs.
  • Whether large errors are concentrated in important samples.
  • Is the extrapolated forecast reasonable?
  • Whether the model has stable generalization performance.

3. Should all outliers be removed?

It shouldn't be.

You need to first determine where the outliers come from:

  • Data entry errors.
  • Measurement abnormalities.
  • A real but rare situation.

Real extreme samples may have business value and cannot be removed just because it makes RMSE larger.

4. Can linear regression only fit straight lines?

no.

"Linear" means that the model is linear with respect to parameters. Through feature engineering such as polynomials, interaction terms, and logarithmic transformations, linear models can also be used to describe certain nonlinear relationships.

5. What is the biggest difference between regression and classification?

  • Regression: Predict continuous values.
  • Classification: Predict discrete classes or class probabilities.

For example, Regression is used to predict house prices, and the Classification problem can be constructed to determine whether house prices exceed a certain threshold.


Summary

Knowledge pointsimportance
Regression / Residual / Losscore
Linear Regression / OLScore
Ridge / L2 Regularizationcore
Lasso / L1 Regularizationcore
ElasticNetimportant
Polynomial Featuresimportant
SVR / Kernel / C / epsilonimportant
MAE / RMSE / R²core
MAPE / Median AECommonly used
Residual Analysiscore
Cross-validationcore
Hyperparameter Tuningimportant
Feature Scalingcore
Overfitting / Data Leakagecore

The five most important concepts of regression analysis:

  1. Least Squares: Fit the model parameters by minimizing the sum of squared residuals.
  2. Regularization: Reduce model complexity by limiting parameter size, Ridge uses L2, Lasso uses L1.
  3. Nonlinear Regression: Polynomial Features and Kernel Methods can describe nonlinear relationships.
  4. Regression Metrics: Use indicators such as MAE, RMSE, R² to evaluate prediction errors from different perspectives.
  5. Generalization: Determine the model's predictive ability on new data through independent test sets, cross-validation and residual analysis.

Reference documentation

Back to top