- Least Squares: Fit the model parameters by minimizing the sum of squared residuals.
- Regularization: Reduce model complexity by limiting parameter size, Ridge uses L2, Lasso uses L1.
- Nonlinear Regression: Polynomial Features and Kernel Methods can describe nonlinear relationships.
- Regression Metrics: Use indicators such as MAE, RMSE, R² to evaluate prediction errors from different perspectives.
- 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 and the continuous target variable :
Among them:
- : Input feature (Features).
- : True target value (Target).
- : model prediction value.
- : model parameters.
- : 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
| Type | Features |
|---|---|
| Linear Regression | Fit the data using a linear relationship |
| Ridge Regression | Add L2 regularization to linear regression |
| Lasso Regression | Add L1 regularization to linear regression |
| Polynomial Regression | Fitting nonlinear relationships using polynomial features |
| Support Vector Regression | Regression using margin and kernel functions |
| Tree-based Regression | Use 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:
Among them:
- : Characteristic coefficient.
- : intercept (Intercept).
- : Number of features.
Ordinary Least Squares(OLS)
Ordinary least squares estimates model parameters by minimizing the sum of squared residuals:
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:
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:
where 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:
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:
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:
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
| model | regularization | Feature selection | Common uses |
|---|---|---|---|
| LinearRegression | None | No | linear baseline model |
| Ridge | L2 | Usually no | More relevant features |
| Lasso | L1 | Yes | Sparse models, feature selection |
| ElasticNet | L1 + L2 | Yes | Balancing 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:
Polynomial regression transforms the original input into polynomial form by constructing new features.
For example:
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:
Quadratic polynomials can generate:
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:
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 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:
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
| parameters | function |
|---|---|
kernel | Kernel function type |
C | Controlling penalties for violating the ε tolerance interval |
epsilon | The width of the insensitive area |
gamma | The 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:
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:
| indicator | Name | optimal direction |
|---|---|---|
| MAE | Mean Absolute Error | The smaller the better |
| MSE | Mean Squared Error | The smaller the better |
| RMSE | Root Mean Squared Error | The smaller the better |
| R² | Coefficient of Determination | The closer to 1 the better |
| MAPE | Mean Absolute Percentage Error | The smaller the better |
| MedAE | Median Absolute Error | The smaller the better |
MAE: mean absolute error
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
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 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
where is the mean of the true values in the evaluation data.
Usually:
- : The prediction was absolutely correct.
- : Same as directly predicting the squared error of the evaluation set mean.
- : 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
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:
Common analysis:
- Whether the actual value is close to the predicted value.
- Is there an obvious trend in the residuals?
- Whether the residuals expand as the predicted value increases.
- Are there extreme outliers?
- 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?
| algorithm | Advantages | limitations | Recommended scenarios |
|---|---|---|---|
| Linear Regression | Simple, explainable, fast to train | Difficult to directly fit complex nonlinearities | Baseline model, linear relationship |
| Ridge | Alleviating collinearity and making coefficients more stable | Most features are not automatically removed | Multiple related features |
| Lasso | Sparse coefficient, feature selection | May be unstable to related features | High-dimensional, sparse features |
| Polynomial Regression | Nonlinearities can be fitted explicitly | High-order features are prone to expansion and overfitting | Low-dimensional, smoother nonlinearity |
| SVR | Supports kernel methods and nonlinear fitting | Parameter adjustment is sensitive and large-scale training is expensive | Small 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 points | importance |
|---|---|
| Regression / Residual / Loss | core |
| Linear Regression / OLS | core |
| Ridge / L2 Regularization | core |
| Lasso / L1 Regularization | core |
| ElasticNet | important |
| Polynomial Features | important |
| SVR / Kernel / C / epsilon | important |
| MAE / RMSE / R² | core |
| MAPE / Median AE | Commonly used |
| Residual Analysis | core |
| Cross-validation | core |
| Hyperparameter Tuning | important |
| Feature Scaling | core |
| Overfitting / Data Leakage | core |
The five most important concepts of regression analysis:
- Least Squares: Fit the model parameters by minimizing the sum of squared residuals.
- Regularization: Reduce model complexity by limiting parameter size, Ridge uses L2, Lasso uses L1.
- Nonlinear Regression: Polynomial Features and Kernel Methods can describe nonlinear relationships.
- Regression Metrics: Use indicators such as MAE, RMSE, R² to evaluate prediction errors from different perspectives.
- Generalization: Determine the model's predictive ability on new data through independent test sets, cross-validation and residual analysis.