Comparing and Selecting Regression Models with Scikit-Learn
A beginner-friendly guide to comparing regression algorithms, evaluating their performance, and selecting the most suitable model for a dataset.
Quick start: If you already understand the concepts and want to try this workflow on your own dataset, jump to Section 10: Complete Code. Replace the CSV filename, configure your target column, and run the implementation in Google Colab.
1. Introduction
In machine learning, we often have several algorithms that can solve the same problem. Suppose we want to predict house prices from:
- House size
- Number of bedrooms
- Number of bathrooms
- Age of the house
- Distance from the city center
We can approach this problem using different regression algorithms:
- Multiple Linear Regression
- Polynomial Regression
- Support Vector Regression (SVR)
- Decision Tree Regression
- Random Forest Regression
But which one should we choose? We usually don't know beforehand, because different algorithms learn patterns differently:
- Some algorithms work well when relationships between variables are approximately linear.
- Some capture curved or more complex relationships.
- Others learn decision-based patterns and interactions between features.
Imagine house prices rise as house size rises. A linear model learns a straight-line relationship: as size increases, price increases at a relatively constant rate. Real-world relationships are not always that simple. A larger house in a premium neighborhood might cost disproportionately more, and a tree-based model can capture that kind of interaction more naturally.
Instead of guessing which algorithm will work best, we can train several models, evaluate their performance, and compare the results. This process is called model selection.
What are we going to do?
Our goal is to identify a regression model that performs well on data it has never seen before. We'll follow this workflow:
- Understand how regression models are evaluated.
- Load and prepare the dataset.
- Separate features (X) and target (y).
- Split into training and test sets.
- Build multiple regression models.
- Compare them using cross-validation.
- Analyze the results and look for overfitting.
- Select the most promising model.
- Optionally improve it with hyperparameter tuning.
- Evaluate the final model on the untouched test set.
Before implementing this workflow, let's understand how we measure a regression model's performance.
2. Understanding Model Evaluation
Before comparing different algorithms, we need a way to measure how well each model performs. A regression model predicts numerical values. We can compare its predictions with the actual values to understand how accurately it performs.
2.1 Understanding Prediction Errors
Imagine our model makes the following predictions:
| Actual price | Predicted price | Absolute error |
|---|---|---|
| 200,000 | 195,000 | 5,000 |
| 300,000 | 310,000 | 10,000 |
| 400,000 | 390,000 | 10,000 |
| 500,000 | 520,000 | 20,000 |
The difference between an actual value and its prediction is called a prediction error or residual.
We calculate it as:
error = actual value - predicted value
Example: 200,000 - 195,000 = 5,000Individual errors do not tell us how the model does overall, so we summarize them with three metrics: MAE, RMSE, and R².
2.2 Mean Absolute Error (MAE)
With thousands of predictions, we cannot inspect every error. We want one number for how far off the predictions are on average. MAE is the average of the absolute errors.
The formula is:
MAE = (1 / n) x sum of |actual - predicted|nis the number of predictions.- Taking the absolute value stops positive and negative errors from cancelling each other out.
Using the table above:
MAE = (5,000 + 10,000 + 10,000 + 20,000) / 4 = 11,250The model's predictions are off by about $11,250 on average.
- Lower MAE is better.
- It uses the same unit as the target.
- Every error counts proportionally; large errors are not penalized extra (unlike RMSE).
2.3 Root Mean Squared Error (RMSE)
MAE treats every dollar of error equally. But sometimes one big mistake is worse than several small ones. Predicting $295,000 instead of $300,000 is minor; predicting $200,000 instead of $300,000 is serious. RMSE penalizes large errors more heavily by squaring them.
RMSE = square root of ( (1 / n) x sum of (actual - predicted)^2 )Step by step with our errors of 5,000, 10,000, 10,000, and 20,000:
- Square each error: 25,000,000; 100,000,000; 100,000,000; 400,000,000.
- Average them (this is the Mean Squared Error, MSE): 625,000,000 / 4 = 156,250,000.
- Take the square root: RMSE = 12,500.
The model's RMSE is $12,500, higher than its MAE of $11,250 because the one $20,000 error carries extra weight.
- Lower RMSE is better.
- It uses the same unit as the target.
- A much larger RMSE than MAE signals that a few large errors are driving the result.
- Prefer it when large mistakes are especially undesirable.
2.4 R² Score (Coefficient of Determination)
MAE and RMSE show how big the errors are, but not how much better our model performs compared with a simple baseline. Imagine always predicting the average house price (say $300,000) no matter what the house looks like. That is our baseline. R² compares the model's squared errors with the baseline's.
R2 = 1 - (sum of squared errors of the model)
/ (sum of squared errors of the mean baseline)In simpler terms, R² says how much of the variation in the target the model accounts for, relative to that baseline.
Its values are generally interpreted as follows:
| R² score | Interpretation |
|---|---|
| 1.0 | Perfect predictions |
| 0.8 | Strong explanatory performance |
| 0.5 | Moderate explanatory performance |
| 0.0 | No improvement over predicting the mean |
| Negative | Worse than predicting the mean |
Important: these labels are only guidelines. What counts as a good R² depends on the problem and field: 0.5 can be useful for predicting human behavior and inadequate when extreme precision is required.
- Higher R² is generally better.
- R² can be negative.
- R² is not the percentage of correct predictions.
- A high R² does not automatically make a model suitable for real-world use.
- R² does not give error sizes in original units, which is why we use MAE and RMSE alongside it.
2.5 Which metrics will we use?
We'll use all three metrics when comparing our regression models.
| Metric | What it tells us | Better result |
|---|---|---|
| MAE | Average absolute prediction error | Lower |
| RMSE | Prediction error, with a greater penalty for large mistakes | Lower |
| R² | Performance relative to the mean-prediction baseline | Higher |
Reading them together:
- Low MAE: predictions are close to the actual values on average.
- RMSE considerably higher than MAE: large errors are influencing the result.
- High R²: the model explains substantially more variation than the baseline.
3. Preparing the Dataset
Before training different algorithms, we need to prepare our dataset.
All models will use the same dataset and the same training and testing sets. This is important because we want to make a fair comparison.
3.1 Importing the Libraries
Let's start by importing the libraries we'll need.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_splitHere's what each library does:
| Library | Purpose |
|---|---|
| NumPy | Numerical calculations and array operations |
| Pandas | Loading and manipulating datasets |
| Matplotlib | Creating visualizations |
| Scikit-learn | Splitting data, training models, and evaluating performance |
3.2 Importing the Dataset
📥 Download the dataset here: UCI Combined Cycle Power Plant dataset
We'll use the UCI Combined Cycle Power Plant dataset. It contains 9,568 observations with four numerical features (ambient temperature, exhaust vacuum, ambient pressure, and relative humidity) and one target: the net hourly electrical energy output (PE). The target is the last column, so the selection code below works without changes.
dataset = pd.read_csv('uci-combined-cycle-power-plant.csv')
dataset.head()Here:
pd.read_csv()loads a CSV file into a Pandas DataFrame.datasetstores the loaded data.head()shows the first five rows.
This helps us understand the structure of our dataset before training any models.
We should also inspect the dataset:
print(dataset.shape)
print(dataset.info())
print(dataset.isnull().sum())These show the number of rows and columns, the column names and data types, and any missing values. Our implementation assumes numerical features with no missing values. Real datasets may need extra preprocessing (Section 8.1).
3.3 Separating Features and Target
A dataset usually contains two kinds of variables:
- Features (X): the input variables used to make predictions (house size, bedrooms, bathrooms, age).
- Target (y): the variable we want to predict (the house price).
Let's separate them:
X = dataset.iloc[:, :-1].values # every column except the last
y = dataset.iloc[:, -1].values # the last columndataset.iloc selects rows and columns by integer position. The first : means every row. In the column part, :-1 means every column except the last, and -1 means only the last column. So X holds all columns but the last, and y holds the last column.
Important: this assumes the target is the last column. If it is somewhere else, select columns explicitly:
X = dataset[['Size', 'Bedrooms', 'Bathrooms']].values
y = dataset['Price'].valuesAlways double-check that you are selecting the right features and target.
3.4 Splitting the Dataset
Could we train on the whole dataset and evaluate on the same data? No. Think of a student who practices a set of questions and then sits an exam containing exactly those questions. A high score does not prove understanding. The same problem occurs in machine learning, so we keep some data the model has never seen:
- Training set: the data the model learns from.
- Test set: data kept aside during training and model selection, used to evaluate the final selected model.
Let's split our dataset:
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=0
)Here:
test_size=0.2reserves 20% of the data for testing; the other 80% is for training.random_state=0gives the same split every time you run the code.
With 1,000 samples, that gives 800 training samples and 200 test samples.
Why keep the test set separate? To evaluate the final model on genuinely unseen data. We compare algorithms on the training set with cross-validation and leave the test set untouched until the end.
Important: train_test_split() shuffles by default. That is fine when observations are independent and similarly distributed. If rows are time-ordered (stock prices, sensor readings), shuffling lets information from the future influence training. Use a chronological split instead (train on earlier rows, test on the latest), and see Section 8.3.
4. Building the Regression Models
Now comes the interesting part. We will create five different regression algorithms and train them on the same data. First, how each one works and when it helps.
4.1 Multiple Linear Regression
Predicts a target from multiple input features, assuming an approximately linear relationship. It learns a coefficient for each feature and combines them into a prediction:
Its general equation is:
y = b0 + b1*x1 + b2*x2 + ... + bn*xnyis the predicted target.x1 ... xnare the input features.b0is the intercept.b1 ... bnare the learned coefficients.
In Scikit-learn:
from sklearn.linear_model import LinearRegression
multiple_linear_regression = LinearRegression()When it helps: relationships are approximately linear, you want a simple and interpretable model, or you need a good baseline for comparison.
4.2 Polynomial Regression
What if the relationship is not a straight line? Suppose house prices rise slowly at first, then much faster as size grows. A linear model struggles with that curve. Polynomial Regression models it by generating extra features from the originals. With one feature x, degree 2 learns y = b0 + b1*x + b2*x^2, and degree 3 adds a b3*x^3 term.
The important thing is that Polynomial Regression still uses a linear regression algorithm. We transform the original features into polynomial features before training the linear model.
Let's implement it using a Scikit-learn pipeline.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.linear_model import LinearRegression
polynomial_regression = Pipeline([
('scale_input', StandardScaler()),
('poly', PolynomialFeatures(
degree=2,
include_bias=False
)),
('scale_poly', StandardScaler()),
('model', LinearRegression())
])The four steps:
- StandardScaler standardizes the original features.
- PolynomialFeatures generates the new ones. With two inputs
x1andx2and degree 2, the set becomesx1, x2, x1^2, x1*x2, x2^2, so the model learns squares and interactions.include_bias=Falseskips an unnecessary constant column. - StandardScaler again, because the generated features can have very different scales.
- LinearRegression trains on the expanded features.
Why a pipeline? It combines preprocessing and the model into one object. During cross-validation, each step is fitted only on the training portion of each fold, which prevents data leakage.
Important: higher degrees create many extra features when there are several inputs. That raises computation cost and the risk of overfitting.
4.3 Support Vector Regression (SVR)
Based on the idea behind Support Vector Machines. Instead of minimizing every error, SVR looks for a function that predicts values while allowing a margin of error, controlled by a parameter called epsilon. Picture a line through the data with a tube around it: predictions inside the tube are acceptable, and only errors outside the tube add to the model's loss.
Different kernels let SVR learn non-linear relationships. We use the Radial Basis Function (RBF) kernel.
from sklearn.svm import SVR
from sklearn.compose import TransformedTargetRegressor
support_vector_regression = TransformedTargetRegressor(
regressor=Pipeline([
('scaler', StandardScaler()),
('model', SVR(kernel='rbf'))
]),
transformer=StandardScaler()
)- Scale the input features. SVR is sensitive to feature scale. If house size ranges from 500 to 5,000, bedrooms from 1 to 6, and age from 1 to 100, the large-valued features dominate distance calculations.
StandardScalerrescales each to roughly mean 0 and standard deviation 1. - Create the SVR model with the RBF kernel.
- Scale the target.
TransformedTargetRegressorscales the target before training and converts predictions back to the original units automatically. SVR settings such asCandepsilondepend on the target's scale: predicting prices in the hundreds of thousands behaves very differently from predicting values between 0 and 1, and an unscaled target often yields an R² near zero or negative. Scaling makes the defaults a reasonable starting point.
Important: SVR can work well on small and medium datasets, but training becomes expensive as the number of samples grows.
4.4 Decision Tree Regression
Instead of fitting an equation, a decision tree learns a set of rules. For house prices, it might ask: is the house larger than 2,000 square feet? Is it in a premium neighborhood? Does it have more than three bedrooms? Each answer splits the data into smaller regions, and each final region (a leaf) gives a numerical prediction.
In Scikit-learn:
from sklearn.tree import DecisionTreeRegressor
decision_tree_regression = DecisionTreeRegressor(
random_state=0
)When it helps: relationships are non-linear, feature interactions matter, you want rule-based decisions, or scaling features is inconvenient.
Important: trees easily overfit. A very deep tree can memorize the training data instead of learning patterns that generalize.
4.5 Random Forest Regression
An ensemble combines several models to make one prediction. Think of asking several people to estimate a house's price instead of trusting one opinion: each guess differs a little, but the average is more reliable. Random Forest applies this idea to decision trees:
- Draw multiple random samples from the training data (bootstrap sampling).
- Train a separate decision tree on each sample.
- Let each tree make its own prediction.
- Average the predictions.
| Decision tree | Predicted price |
|---|---|
| Tree 1 | $290,000 |
| Tree 2 | $310,000 |
| Tree 3 | $300,000 |
| Tree 4 | $320,000 |
| Tree 5 | $280,000 |
Final prediction: (290,000 + 310,000 + 300,000 + 320,000 + 280,000) / 5 = $300,000.
Averaging many trees generally makes the forest more stable than a single tree.
In Scikit-learn:
from sklearn.ensemble import RandomForestRegressor
random_forest_regression = RandomForestRegressor(
n_estimators=100,
random_state=0
)Here:
n_estimators=100means 100 decision trees.random_state=0makes the model reproducible.
When it helps: complex non-linear relationships, important feature interactions, a strong general-purpose baseline, or when you do not want to transform features by hand.
Important: forests generally need no feature scaling, but they can be computationally expensive and are less interpretable than simpler models.
5. Comparing Models Using Cross-Validation
We now have five different regression algorithms. We could train each one and score it on a single train-test split, but the result may depend heavily on which samples landed where. Random Forest might look great on one split, SVR better on another, and the Decision Tree poor because the test set held unusual rows. To get a more reliable estimate, we use cross-validation.
5.1 What Is Cross-Validation?
We reserved the test set for the final evaluation, but we still need a way to compare the five models using the training set. Splitting the training set once more into training and validation parts would still depend on one particular split. Cross-validation evaluates the model across several different splits. The most common version is K-fold cross-validation.
Suppose the training set has 800 samples and we use 5 folds.
- Divide the training set into five equal parts called folds, about 160 samples each.
- Train on four folds and validate on the remaining one. In iteration 1, folds 2 to 5 train and fold 1 validates.
- Repeat five times, using a different fold for validation each time.
- Average the five validation scores.
| Iteration | Fold 1 | Fold 2 | Fold 3 | Fold 4 | Fold 5 |
|---|---|---|---|---|---|
| 1 | Validation | Train | Train | Train | Train |
| 2 | Train | Validation | Train | Train | Train |
| 3 | Train | Train | Validation | Train | Train |
| 4 | Train | Train | Train | Validation | Train |
| 5 | Train | Train | Train | Train | Validation |
Every sample is used for validation once and for training the rest of the time. We get five validation scores instead of one. Their average estimates how well the model generalizes, and their standard deviation shows how much performance varies across folds.
5.2 Preparing the Models
Instead of writing separate evaluation code for each algorithm, store the models in a dictionary. Later, we loop through it and evaluate every model with the same code. Adding or removing a model becomes as simple as adding or removing an entry.
models = {
'Multiple Linear Regression': multiple_linear_regression,
'Polynomial Regression': polynomial_regression,
'Support Vector Regression': support_vector_regression,
'Decision Tree Regression': decision_tree_regression,
'Random Forest Regression': random_forest_regression
}5.3 Performing Cross-Validation
Scikit-learn provides a function called cross_validate() that allows us to evaluate a model using cross-validation and multiple evaluation metrics.
First, let's define our metrics:
scoring = {
'mae': 'neg_mean_absolute_error',
'rmse': 'neg_root_mean_squared_error',
'r2': 'r2'
}Why neg_ for MAE and RMSE? Scikit-learn follows one convention: higher scores are better. For MAE and RMSE, lower is better, so it returns them as negative numbers (an MAE of 10 becomes -10). We multiply by -1 when presenting results.
Next, let's define our cross-validation strategy.
from sklearn.model_selection import cross_validate, KFold
cv = KFold(
n_splits=5,
shuffle=True,
random_state=0
)Here:
n_splits=5divides the training data into five folds.shuffle=Trueshuffles the data before creating folds.random_state=0makes the folds reproducible.
Now let's evaluate all our models.
results = []
for name, model in models.items():
scores = cross_validate(
model,
X_train,
y_train,
cv=cv,
scoring=scoring,
return_train_score=True
)
results.append({
'Model': name,
'MAE': -scores['test_mae'].mean(),
'RMSE': -scores['test_rmse'].mean(),
'RMSE std': scores['test_rmse'].std(),
'R2': scores['test_r2'].mean(),
'Train R2': scores['train_r2'].mean()
})What the loop does:
results = []is an empty list that will hold every model's results.for name, model in models.items()walks through the dictionary.cross_validate(...)evaluates the current model.cv=cvuses our five-fold strategy,scoring=scoringcomputes MAE, RMSE, and R², andreturn_train_score=Truealso returns training scores for each fold.results.append(...)stores the summary values.
Let's understand what we're collecting.
| Result | Meaning |
|---|---|
| MAE | Average validation MAE across folds |
| RMSE | Average validation RMSE across folds |
| RMSE std | Standard deviation of validation RMSE across folds |
| R² | Average validation R² across folds |
| Train R² | Average training R² across folds |
-scores['test_rmse'].mean() averages the validation RMSE and flips it back to a positive value. scores['test_rmse'].std() measures how much RMSE varies across the five folds.
Why collect training scores? If a model does extremely well on training data but poorly on validation data, it may be overfitting. We compare the two in the next section.
Finally, let's convert our results into a Pandas DataFrame.
results_df = pd.DataFrame(results)
results_df = results_df.sort_values(
by='RMSE',
ascending=True
).reset_index(drop=True)
results_dfsort_values() sorts by RMSE with the lowest first, and reset_index(drop=True) renumbers the rows. We now have a comparison table of all five models.
5.4 Understanding the Results
Suppose our results look something like this:
These are illustrative results, not actual model outputs. Errors are expressed in thousands of dollars.
| Model | MAE | RMSE | RMSE std | R² | Train R² |
|---|---|---|---|---|---|
| Random Forest | 8.5 | 13.7 | 1.1 | 0.91 | 0.98 |
| Polynomial | 9.8 | 15.4 | 1.9 | 0.88 | 0.90 |
| SVR | 11.2 | 17.1 | 1.4 | 0.85 | 0.87 |
| Multiple Linear | 12.5 | 18.2 | 1.3 | 0.82 | 0.83 |
| Decision Tree | 14.6 | 22.3 | 3.0 | 0.73 | 1.00 |
Let's understand what these results tell us.
Random Forest has the lowest MAE and RMSE, the highest validation R², and a small RMSE standard deviation, so it is our leading candidate. Its training R² (0.98) is higher than its validation R² (0.91). That gap is normal for forests: each tree sees most of the training rows, so a forest's training score always looks flattering. Judge a forest by its validation score, which is still strong here.
Decision Tree has a training R² of 1.00 but a validation R² of only 0.73, and the largest RMSE standard deviation. This is a strong sign of overfitting: it nails the data it has seen and struggles on unseen samples.
Polynomial Regression has training and validation R² close together (0.90 and 0.88), suggesting more consistent generalization in this example.
What Does RMSE Standard Deviation Tell Us?
Cross-validation produces five RMSE scores, for example:
Fold 1: 12.5
Fold 2: 13.0
Fold 3: 14.0
Fold 4: 13.5
Fold 5: 15.0The average is the model's overall validation error. The standard deviation shows how much the five scores vary around that average. A lower value generally means more consistent performance across folds; a higher value means more fold-to-fold swing. A low standard deviation does not make a model better by itself, so always read it alongside the average error.
This is a descriptive measure of fold-to-fold variation, not a formal statistical significance test. The folds are not fully independent because their training portions overlap.
How Do We Decide Which Model Is Best?
We shouldn't select a model using only one metric. Consider:
- MAE: How large are the average absolute prediction errors?
- RMSE: Are large prediction errors a concern?
- R²: How well does the model perform relative to the mean-prediction baseline?
- RMSE standard deviation: Is performance consistent across folds?
- Train R² vs validation R²: Is there evidence of overfitting?
In our example, Random Forest leads on the main metrics. If two models perform similarly, prefer the simpler one: it is easier to understand, faster, and easier to maintain.
6. Selecting and Evaluating the Best Model
After comparing our models using cross-validation, we need to select the most promising candidate. By default, we'll select the model with the lowest average cross-validation RMSE.
6.1 Selecting the Best Model
Let's find the model with the lowest RMSE.
best_model_name = results_df.loc[
results_df['RMSE'].idxmin(),
'Model'
]
best_model = models[best_model_name]
print('Selected Model:', best_model_name)results_df['RMSE'].idxmin() returns the index of the row with the lowest RMSE, .loc[] reads the model name from that row, and models[best_model_name] fetches the matching model from our dictionary.
What If Two Models Perform Almost Equally Well?
Suppose our results look like this:
| Model | Average RMSE |
|---|---|
| Random Forest | 13.7 |
| Polynomial Regression | 14.0 |
| SVR | 14.2 |
Random Forest has the lowest RMSE, but the gaps are small. Should we always pick the lowest score? Not necessarily: a slightly more complex model may perform almost the same as a simpler one.
A useful heuristic is the one-standard-error rule. It gives us a way to create a shortlist of models whose average errors are close to the best model's error.
Let's calculate it.
best_row = results_df.loc[results_df['RMSE'].idxmin()]
best_se = best_row['RMSE std'] / np.sqrt(cv.get_n_splits())
threshold = best_row['RMSE'] + best_se
shortlist = results_df[results_df['RMSE'] <= threshold]
shortlist[['Model', 'RMSE', 'RMSE std']]Here:
best_rowholds the best model's results.- Dividing its RMSE standard deviation by the square root of the number of folds gives an approximate standard error.
thresholdis the largest RMSE allowed on the shortlist.
Important: this is a practical heuristic, not proof that the shortlisted models are statistically equivalent. Ordinary K-fold scores are correlated, so the calculated standard error should not be treated as a formal confidence interval.
If a simpler model is on the shortlist and its performance is acceptable, we may prefer it. In that case, set best_model_name to its name and best_model = models[best_model_name].
6.2 Checking for Overfitting
Before finalizing our model, let's examine its training and validation performance.
Remember:
- Training performance is how well the model does on the data used to train it.
- Validation performance estimates how well it does on unseen data during cross-validation.
Comparing them reveals possible overfitting and underfitting.
| Situation | Possible interpretation |
|---|---|
| High training R² and similarly high validation R² | Good generalization may be possible |
| Training R² much higher than validation R² | Possible overfitting |
| Both training and validation R² low | Possible underfitting or weak features |
For our illustrative results:
| Model | Train R² | Validation R² | Observation |
|---|---|---|---|
| Random Forest | 0.98 | 0.91 | Normal for forests; trust the validation score |
| Polynomial | 0.90 | 0.88 | Relatively good generalization |
| Decision Tree | 1.00 | 0.73 | Strong overfitting |
These are simplified interpretations. Similar scores do not guarantee that a model has learned meaningful relationships, and a high R² does not rule out other problems.
6.3 Training the Selected Model
During cross-validation, each individual model was trained using only a portion of the training dataset. Now that we've selected our model, we want it to learn from the entire training dataset.
best_model.fit(X_train, y_train)This trains the selected model using all available training samples.
For models built with pipelines, the preprocessing steps are also fitted using the entire training dataset.
6.4 Predicting the Test Set Results
Now let's use our trained model to make predictions on the test dataset. Remember, the test dataset has remained untouched during model comparison.
y_pred = best_model.predict(X_test)X_test holds the unseen features, predict() generates predictions, and y_pred stores them. To compare predictions with reality:
comparison = pd.DataFrame({
'Predicted': y_pred,
'Actual': y_test
})
comparison.head(10)This shows the first ten predicted and actual values side by side.
6.5 Evaluating the Final Model
Now let's calculate the evaluation metrics on the test dataset.
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score
)
mae = mean_absolute_error(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
print('Final Model Evaluation')
print('----------------------')
print('Selected Model:', best_model_name)
print('MAE:', mae)
print('RMSE:', rmse)
print('R2 Score:', r2)These metrics show how well the selected model performs on previously unseen data.
Why evaluate the test set only at the end? The test set must represent genuinely unseen data. If you repeatedly check test results to choose models or adjust settings, information from the test set starts to influence your decisions, and the final evaluation becomes less reliable. The correct workflow:
- Compare models with cross-validation on the training set.
- Select a model using the validation results.
- Optionally tune its hyperparameters using cross-validation.
- Evaluate the final selected model once on the untouched test set.
6.6 Comparing Cross-Validation and Test Performance
We can now compare the cross-validation performance with the final test performance.
| Evaluation | RMSE |
|---|---|
| Cross-validation | 13.7 |
| Test | 14.2 |
If the two are reasonably close, as above, the cross-validation estimate was representative of the test data. If the test RMSE is considerably higher, possible explanations include:
- The model overfits the training data.
- The test set contains different patterns.
- The training and test samples come from different distributions.
- The dataset is small, making estimates unstable.
A difference is not automatically a bug. It is a signal to investigate the data and the model further.
7. Visualizing and Improving the Model Comparison
Numbers are useful, but visualizations can make model comparisons easier to understand.
7.1 Visualizing Model Performance
A bar chart of cross-validation RMSE makes the comparison easier to see. We'll also display error bars representing the standard deviation across folds.
plt.figure(figsize=(10, 5))
plt.bar(
results_df['Model'],
results_df['RMSE'],
yerr=results_df['RMSE std'],
capsize=4
)
plt.title('Regression Model Comparison')
plt.xlabel('Regression Models')
plt.ylabel('Cross-Validation RMSE')
plt.xticks(rotation=30, ha='right')
plt.tight_layout()
plt.show()Each bar is a model; its height is the average cross-validation RMSE, and its error bars show the fold-to-fold standard deviation.
- Lower bars mean smaller prediction errors.
- Shorter error bars mean more consistent performance.
- Similar bar heights suggest similar average RMSE, but overlapping error bars do not prove the models are statistically equivalent.
You can draw similar charts for MAE and R².
7.2 Understanding Hyperparameters
So far we compared models mostly with default settings. But every algorithm has settings that control how it learns. Two terms to keep apart:
- Parameters are values the model learns during training. Linear Regression learns a coefficient for each feature.
- Hyperparameters are settings chosen before or during model selection that control the learning process.
| Algorithm | Important hyperparameters |
|---|---|
| Polynomial Regression | degree |
| SVR | C, epsilon, gamma, kernel |
| Decision Tree | max_depth, min_samples_split, min_samples_leaf |
| Random Forest | n_estimators, max_depth, min_samples_leaf |
A model that looks weak with default settings might perform much better after tuning.
7.3 What is Hyperparameter Tuning?
Finding suitable hyperparameter values for a model. For a Random Forest, we could try:
n_estimators: 100 or 300max_depth: None, 5, or 10min_samples_leaf: 1 or 3
Each combination is a different model configuration, and there are 2 x 3 x 2 = 12 of them. Scikit-learn can automate trying them using a tool called grid search.
7.4 What is grid search?
Grid search tries every combination from a predefined search space, evaluates each with cross-validation, and reports the best according to your chosen metric.
from sklearn.model_selection import GridSearchCV
param_grid = {
'n_estimators': [100, 300],
'max_depth': [None, 5, 10],
'min_samples_leaf': [1, 3]
}
grid = GridSearchCV(
RandomForestRegressor(random_state=0),
param_grid,
cv=cv,
scoring='neg_root_mean_squared_error',
n_jobs=-1
)
grid.fit(X_train, y_train)
print('Best Parameters:', grid.best_params_)
print('Best CV RMSE:', -grid.best_score_)param_gridlists the hyperparameter values to try.RandomForestRegressor(random_state=0)is the estimator being tuned.cv=cvreuses our five-fold strategy.scoringtells grid search to optimize RMSE.n_jobs=-1uses all available CPU cores.grid.fit(...)evaluates all 12 combinations with cross-validation.grid.best_params_is the best combination;grid.best_score_is its average cross-validation RMSE as a positive number.
Retrieve the best model:
best_model = grid.best_estimator_By default GridSearchCV uses refit=True, so the best configuration is already retrained on the entire training set. Evaluate it on the test set with the code from Section 6.5.
Important: this example tunes Random Forest. If another algorithm wins, tune that one with its own grid. Parameter names depend on the model structure:
| Model | Example grid search parameters |
|---|---|
| Polynomial Regression | poly__degree |
| SVR | regressor__model__C, regressor__model__gamma, regressor__model__epsilon |
| Decision Tree | max_depth, min_samples_split |
| Random Forest | n_estimators, max_depth, min_samples_leaf |
The double underscore (__) reaches into pipelines and nested estimators. For example, 'poly__degree' is the degree parameter of the pipeline step named poly.
7.5 Grid Search vs. Randomized Search
Grid search tries every combination. It is expensive when the search space is large and works well when the number of combinations is manageable.
Randomized search (RandomizedSearchCV) samples a fixed number of random combinations. It explores large spaces more efficiently but does not guarantee every combination is tested. For big search spaces, it is often a good starting point.
Important: Hyperparameter tuning introduces another layer of model selection. The best cross-validation score found during tuning may be optimistic because we chose the configuration using those same validation results. For more rigorous evaluation, nested cross-validation can be used. For our beginner workflow, we keep the test set untouched and use it only for the final evaluation.
8. Important Considerations
Before using this workflow on a real-world dataset, keep the following points in mind.
8.1 Data preprocessing
Our implementation assumes that the dataset contains numerical features without missing values. However, real-world datasets are often more complicated. They may contain:
- Missing values
- Categorical variables
- Duplicate records
- Outliers
- Features with different scales
Handle these before training.
- Missing values:
SimpleImputerfills them using the mean, median, or most frequent value. - Categorical variables: text columns such as
City(Dhaka, Chittagong, Sylhet) must become numbers.OneHotEncoderconverts each category into numerical columns. - Feature scaling:
StandardScalerstandardizes numerical features.
Why pipelines and ColumnTransformer? When preprocessing is performed before cross-validation, information from validation folds can accidentally influence preprocessing. For example, calculating the mean of a feature using the entire dataset before cross-validation allows validation data to influence the imputation value. This is a form of data leakage. Using Pipeline and ColumnTransformer ensures that preprocessing is fitted separately within each training fold. This is the recommended approach for more complex real-world datasets.
8.2 Feature Scaling
Feature scaling is the process of transforming numerical features so that they have comparable scales. Some algorithms are sensitive to feature scales, while others generally aren't.
| Algorithm | Feature scaling |
|---|---|
| Multiple Linear Regression | Usually not required |
| Polynomial Regression | Helpful |
| SVR | Usually required |
| Decision Tree | Not required |
| Random Forest | Not required |
Why? Imagine house size from 500 to 5,000, bedrooms from 1 to 6, and age from 1 to 100. Algorithms that rely on distances or margins let large-range features dominate, and StandardScaler fixes that. Tree-based algorithms decide using thresholds on one feature at a time, so scale does not affect them the same way.
8.3 Choosing the Right Cross-Validation Strategy
We used KFold, a reasonable starting point when observations are independent and similarly distributed. Not every dataset fits it.
Different datasets may require different splitting strategies.
| Dataset type | Suitable strategy |
|---|---|
| Ordinary independent observations | KFold |
| Time-series data | TimeSeriesSplit |
| Grouped observations | GroupKFold |
Time-series data. Suppose we predict future stock prices from history. If we shuffle randomly, the model may train on future observations while validating on earlier ones, which is unrealistic. Train on earlier observations and validate on later ones. TimeSeriesSplit does this.
Grouped data. Suppose a medical dataset has several records per patient. If some of a patient's records are in training and others in validation, the evaluation becomes overly optimistic. GroupKFold keeps each group together, so related records never appear in both training and validation within one split.
The initial train-test split must also respect the time or group structure. Changing only the cross-validation strategy is not enough.
8.4 Overfitting and Underfitting
Overfitting happens when a model learns the training data too closely, memorizing details and noise instead of general patterns. Training performance is very high while validation or test performance is much worse. An unrestricted Decision Tree can memorize its training samples.
Underfitting happens when a model is too simple to capture the important patterns. Both training and validation performance are poor. A simple linear model facing a highly non-linear relationship may underfit.
We identify both by comparing training and validation performance. Cross-validation helps estimate how well a model generalizes.
8.5 Model Selection Can Also Overfit
Suppose we compare 50 algorithms with cross-validation and keep the one with the best score. Even if each was evaluated correctly, the winning score may be overly optimistic, because we chose the winner using those same validation results. Some models get unusually favorable scores simply from how the data was divided. This is selection bias.
For a beginner workflow, comparing a small number of reasonable candidates and keeping an untouched test set is a practical start. For extensive model selection and tuning, nested cross-validation is the more rigorous approach.
8.6 The Highest Score Is Not Always the Best Choice
Imagine we have two models:
| Model | RMSE | Training time |
|---|---|---|
| Model A | 12.5 | 2 seconds |
| Model B | 12.3 | 30 seconds |
Model B has slightly lower RMSE but takes far longer to train. Is the tiny gain worth the cost? It depends on the problem. Consider:
- Prediction accuracy
- Training time and prediction speed
- Model complexity
- Interpretability
- Memory and computational requirements
The best model satisfies the actual requirements of the problem, not necessarily the highest score.
8.7 Which Model Should We Try?
The evaluation results should guide our decision, but the following table provides some useful starting points.
| Situation | Model worth trying |
|---|---|
| Approximately linear relationship, interpretability matters | Multiple Linear Regression |
| Smooth curved relationship | Polynomial Regression |
| Small or medium dataset with non-linear patterns | SVR |
| You need understandable decision rules | Decision Tree |
| Complex interactions and non-linear patterns | Random Forest |
These are starting points, not strict rules. Real performance depends on the dataset, features, data quality, and problem requirements.
8.8 Environment and Version Notes
Some Scikit-learn features depend on the installed version:
neg_root_mean_squared_errorneeds Scikit-learn 0.22 or newer.root_mean_squared_errorneeds 1.4 or newer. Our code usesnp.sqrt(mean_squared_error(...))instead, so it does not depend on it.display()works in Colab and Jupyter. Elsewhere, useprint().
Check your version:
import sklearn
print(sklearn.__version__)9. Checklist and Glossary
9.1 Checklist for a New Dataset
Whenever you compare regression models on a new dataset, work through this list.
Dataset preparation
- Load the dataset and inspect its structure.
- Identify the feature columns and the target column.
- Check for missing values.
- Identify categorical features.
- Check for duplicate records and unusual values.
- Handle preprocessing requirements.
- Determine whether the dataset contains time-ordered or grouped observations.
Model training and comparison
- Split into training and test sets.
- Prepare the candidate regression models.
- Use suitable preprocessing pipelines.
- Choose an appropriate cross-validation strategy.
- Compare models using cross-validation.
- Review MAE, RMSE, and R².
- Examine performance variability.
- Check for overfitting and underfitting.
Model selection and evaluation
- Select the most promising model.
- Consider model complexity and computational requirements.
- Optionally tune the hyperparameters of promising candidates.
- Keep the test set untouched during model selection.
- Evaluate the final model once on the test set.
- Investigate large gaps between validation and test performance.
- Retrain the finalized model on all available labeled data before deployment.
9.2 Glossary
| Term | Meaning |
|---|---|
| Feature | An input variable used for prediction (X). |
| Target | The variable we want to predict (y). |
| Fit / Train | Letting a model learn patterns from data with .fit(). |
| Predict | Using a trained model to generate predictions with .predict(). |
| Training set | Data used to train the model. |
| Validation set | Data used to evaluate a model during development. |
| Test set | Data reserved for final model evaluation. |
| Fold | One portion of a dataset used during cross-validation. |
| Cross-validation | Evaluating a model across multiple data splits. |
| K-fold | A cross-validation strategy that divides data into K folds. |
| MAE | Average absolute prediction error. |
| RMSE | Prediction error that penalizes large mistakes more heavily. |
| R² | A measure of performance relative to a mean-prediction baseline. |
| Residual | The difference between an actual value and its prediction. |
| Parameter | A value learned by the model during training. |
| Hyperparameter | A setting that controls the learning process. |
| Hyperparameter tuning | Searching for suitable hyperparameter values. |
| Pipeline | A sequence of preprocessing steps and a model treated as one estimator. |
| Data leakage | Information from held-out data influencing training or preprocessing. |
| Overfitting | Learning the training data too closely, resulting in poor generalization. |
| Underfitting | Failing to learn important patterns because the model is too simple. |
| Model selection | Comparing candidate models to choose a suitable algorithm. |
| Selection bias | An optimistic result caused by picking a winner using the same results that score it. |
| Ensemble learning | Combining multiple models to produce predictions. |
| Grid search | Trying every combination of specified hyperparameter values. |
| Randomized search | Evaluating a fixed number of randomly chosen hyperparameter combinations. |
10. Complete Code: Regression Model Selection
Here is everything in one implementation. Copy it into a Google Colab notebook (one cell per subsection works well), provide your dataset, and run it. It will:
- Load the dataset and separate features and target.
- Split into training and test sets.
- Create five regression models.
- Compare them with five-fold cross-validation.
- Display MAE, RMSE, R², variability, and training R².
- Select the best model and a shortlist of models close to it.
- Optionally tune the top candidates.
- Evaluate the final model on the test set.
- Visualize the comparison.
Before running:
- 📥 Download the dataset here: UCI Combined Cycle Power Plant dataset and place it in your working directory.
- The filename is already set to
uci-combined-cycle-power-plant.csv; change it if you saved the file under a different name. - The target (PE) is already the last column, so no column changes are needed (otherwise see Section 3.3).
- All features are numerical, and the dataset has no missing values, so no preprocessing is required to run the workflow as-is.
- If you use a different dataset, make sure all features are numerical and handle missing values first.
- If your data is time-ordered or grouped, adapt the splitting strategy (Section 8.3).
- If you have fewer than five training samples, reduce the number of folds.
10.1 Importing Libraries and Loading the Dataset
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import (
train_test_split,
cross_validate,
KFold,
GridSearchCV
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import (
StandardScaler,
PolynomialFeatures
)
from sklearn.compose import TransformedTargetRegressor
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score
)
# ---- Load dataset ----
dataset = pd.read_csv('uci-combined-cycle-power-plant.csv')
# ---- Inspect dataset ----
print('Dataset Shape:', dataset.shape)
display(dataset.head())
# ---- Separate features and target ----
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values10.2 Splitting the Dataset
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=0
)
print('Training Samples:', len(X_train))
print('Testing Samples:', len(X_test))10.3 Defining the Regression Models
models = {
'Multiple Linear Regression': LinearRegression(),
'Polynomial Regression': Pipeline([
('scale_input', StandardScaler()),
('poly', PolynomialFeatures(
degree=2,
include_bias=False
)),
('scale_poly', StandardScaler()),
('model', LinearRegression())
]),
'Support Vector Regression': TransformedTargetRegressor(
regressor=Pipeline([
('scaler', StandardScaler()),
('model', SVR(kernel='rbf'))
]),
transformer=StandardScaler()
),
'Decision Tree Regression': DecisionTreeRegressor(
random_state=0
),
'Random Forest Regression': RandomForestRegressor(
n_estimators=100,
random_state=0
)
}10.4 Comparing Models Using Cross-Validation
# ---- Define evaluation metrics ----
scoring = {
'mae': 'neg_mean_absolute_error',
'rmse': 'neg_root_mean_squared_error',
'r2': 'r2'
}
# ---- Define cross-validation strategy ----
cv = KFold(
n_splits=5,
shuffle=True,
random_state=0
)
# ---- Evaluate all models ----
results = []
for name, model in models.items():
scores = cross_validate(
model,
X_train,
y_train,
cv=cv,
scoring=scoring,
return_train_score=True
)
results.append({
'Model': name,
'MAE': -scores['test_mae'].mean(),
'RMSE': -scores['test_rmse'].mean(),
'RMSE std': scores['test_rmse'].std(),
'R2': scores['test_r2'].mean(),
'Train R2': scores['train_r2'].mean()
})
# ---- Create comparison table ----
results_df = pd.DataFrame(results)
results_df = results_df.sort_values(
by='RMSE',
ascending=True
).reset_index(drop=True)
print('Model Comparison (Cross-Validation)')
display(results_df)10.5 Selecting the Best Model
# ---- Find the model with the lowest RMSE ----
best_row = results_df.loc[
results_df['RMSE'].idxmin()
]
best_model_name = best_row['Model']
print('Best Model:', best_model_name)
# ---- One-standard-error heuristic ----
best_se = best_row['RMSE std'] / np.sqrt(
cv.get_n_splits()
)
threshold = best_row['RMSE'] + best_se
shortlist = results_df[
results_df['RMSE'] <= threshold
]
print('\nModels Close to the Best:')
display(
shortlist[['Model', 'RMSE', 'RMSE std']]
)
# ---- Select the default winner ----
# You can manually select a simpler model from
# the shortlist if its performance is acceptable.
best_model = models[best_model_name]
print('\nSelected Model:', best_model_name)10.6 Optional: Hyperparameter Tuning
This cell tunes the top three candidates from the comparison. Tuning every model can be expensive, so a shortlist is a practical compromise for a beginner workflow. But a model that performs poorly with default settings may become competitive after tuning, so if that is a realistic possibility, tune all of them. Skip the cell to use the untuned selection from 10.5.
# ---- Define hyperparameter grids ----
param_grids = {
'Multiple Linear Regression': {},
'Polynomial Regression': {
'poly__degree': [2, 3, 4]
},
'Support Vector Regression': {
'regressor__model__C': [1, 10, 100],
'regressor__model__epsilon': [0.01, 0.1, 0.2],
'regressor__model__gamma': ['scale', 'auto']
},
'Decision Tree Regression': {
'max_depth': [None, 5, 10, 20],
'min_samples_split': [2, 5, 10],
'min_samples_leaf': [1, 2, 4]
},
'Random Forest Regression': {
'n_estimators': [100, 200, 300],
'max_depth': [None, 5, 10, 20],
'min_samples_leaf': [1, 2, 4]
}
}
# ---- Choose how many models to tune ----
top_k = 3 # use 1 to tune only the winner, or 5 for all
tuned = []
# ---- Tune the top candidates ----
for name in results_df['Model'].head(top_k):
grid = GridSearchCV(
estimator=models[name],
param_grid=param_grids[name],
cv=cv,
scoring='neg_root_mean_squared_error',
n_jobs=-1
)
grid.fit(X_train, y_train)
tuned.append({
'Model': name,
'Tuned CV RMSE': -grid.best_score_,
'Best params': grid.best_params_,
'Estimator': grid.best_estimator_
})
# ---- Compare tuned models ----
tuned_df = pd.DataFrame(tuned)
tuned_df = tuned_df.sort_values(
by='Tuned CV RMSE',
ascending=True
).reset_index(drop=True)
print('Tuned Model Comparison')
display(tuned_df[['Model', 'Tuned CV RMSE', 'Best params']])
# ---- Select the best tuned model ----
best_model_name = tuned_df.loc[0, 'Model']
best_model = tuned_df.loc[0, 'Estimator']
print('\nSelected Model after Tuning:', best_model_name)Important: grid search already refitted each best estimator on the entire training set (refit=True is the default). The tuned cross-validation scores are for choosing the final candidate, not an unbiased estimate of its performance. The untouched test set remains the final evaluation.
10.7 Final Evaluation on the Test Dataset
Whether you use the untuned or the tuned model, the final evaluation happens here, once.
# ---- Train on the full training set ----
# This is harmless even if GridSearchCV already refitted
# the selected estimator.
best_model.fit(X_train, y_train)
# ---- Predict test results ----
y_pred = best_model.predict(X_test)
# ---- Calculate evaluation metrics ----
mae = mean_absolute_error(y_test, y_pred)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
# ---- Display results ----
print('Final Model Evaluation')
print('----------------------')
print('Selected Model:', best_model_name)
print('MAE:', mae)
print('RMSE:', rmse)
print('R2 Score:', r2)10.8 Comparing Predicted and Actual Values
comparison = pd.DataFrame({
'Predicted': y_pred,
'Actual': y_test
})
print('Predicted vs Actual Values')
display(comparison.head(10))10.9 Visualizing Model Comparison
plt.figure(figsize=(10, 5))
plt.bar(
results_df['Model'],
results_df['RMSE'],
yerr=results_df['RMSE std'],
capsize=4
)
plt.title('Regression Model Comparison')
plt.xlabel('Regression Models')
plt.ylabel('Cross-Validation RMSE')
plt.xticks(rotation=30, ha='right')
plt.tight_layout()
plt.show()What do we get from this notebook?
- Five regression algorithms trained and compared.
- Cross-validation MAE, RMSE, and R² for every model.
- A measure of performance variability across folds.
- Training and validation scores to spot possible overfitting.
- A shortlist of models close to the best candidate.
- An automatically selected model based on cross-validation RMSE.
- Optional hyperparameter tuning for the top candidates.
- A final evaluation on previously unseen test data.
- A chart comparing the models.
11. Final thoughts
We have learned how to compare regression algorithms and select a suitable model for a dataset. The most important lesson is that there is no universally best regression algorithm. Multiple Linear Regression might work well on one dataset and Random Forest on another.
The right approach is to:
- Understand your dataset.
- Choose reasonable candidate algorithms.
- Evaluate them with an appropriate cross-validation strategy.
- Compare performance using multiple metrics.
- Consider overfitting, stability, complexity, and computational requirements.
- Tune promising candidates when necessary.
- Evaluate the final model on an untouched test set.
Remember: the model with the lowest cross-validation RMSE is a starting choice, not automatically the best solution for every real-world problem. Once the model is finalized and evaluated, retrain it on all available labeled data (X, y) before using it to predict genuinely new data.
The goal is not the most complicated algorithm or the highest score. It is a model that learns meaningful patterns and makes reliable predictions on data it has never seen before.