(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisbon

How to detect redundant features in Machine Learning: step by step

João Barros 24 de November de 2026 5 min read

This tutorial shows how to identify and remove redundant features (highly correlated or collinear) in Machine Learning, a useful task to reduce overfitting, improve performance and speed up training. We will explain why these techniques matter and present a practical workflow with complementary methods: correlation to detect pairs, Variance Inflation Factor (VIF) for multivariate collinearity, and an iterative removal approach. We use Python with pandas, numpy, scikit-learn and statsmodels to illustrate with a synthetic example that yields quick results.

Prerequisites

  • Python 3.8+ installed
  • Libraries: pandas, numpy, scikit-learn, statsmodels (install with pip, for example: pip install pandas numpy scikit-learn statsmodels)
  • Basic concepts of regression/classification and preprocessing

It is useful to have notions of cross-validation and how to interpret metrics (e.g.: R2, AUC). For datasets with hundreds of thousands of rows or many columns, consider sampling and measuring performance (time/memory) before applying VIF to everything.

Step 1: Understand why to detect redundant features

Redundant features are variables that carry very similar information. Keeping them can introduce collinearity, make linear model interpretation harder (unstable coefficients), and increase training time. In more complex models (e.g.: RandomForest) redundancy can make variable importance less reliable. Detecting and removing redundancies helps simplify models, reduce the risk of overfitting and improve explainability.

Some practical rules: for linear pairs consider correlation thresholds above 0.8–0.9; for VIF values above 5 pay attention, above 10 are often unacceptable. However, the threshold and decision depend on context: if two redundant variables are both important for prediction, you may prefer regularization techniques (Lasso/Ridge) instead of removing information.

Step 2: Prepare the data (minimal example)

Load an example dataset (CSV or generated). Here we create a DataFrame with intentionally redundant variables to test the methods. We use n=200 observations to keep calculations fast and reproducible (np.random.seed(0)).

import numpy as np
import pandas as pd

np.random.seed(0)
n = 200
X1 = np.random.normal(size=n)
X2 = X1 * 0.95 + np.random.normal(scale=0.1, size=n)  # altamente correlacionada com X1
X3 = np.random.normal(size=n)
X4 = X3 * -0.8 + np.random.normal(scale=0.2, size=n)  # correlacionada com X3
X5 = np.random.normal(size=n)

df = pd.DataFrame({
    'X1': X1,
    'X2': X2,
    'X3': X3,
    'X4': X4,
    'X5': X5,
})

y = 2*X1 + 0.5*X3 + np.random.normal(size=n)

Step 3: Detect highly correlated pairs (correlation matrix)

Pearson correlation reveals pairs with a strong linear relationship. Compute the matrix and apply a threshold (e.g.: 0.85) to flag redundancy. In many cases, we will prefer to keep only one of the variables in a pair with very high correlation. For example, if X1 and X2 have correlation 0.97, we can remove X2 and keep X1.

# matriz de correlação absoluta
corr = df.corr().abs()
# criar máscara para triângulo superior (evitar duplicados)
upper = corr.where(np.triu(np.ones(corr.shape), k=1).astype(bool))
# listar colunas com correlação acima do limiar
threshold = 0.85
to_drop_corr = [column for column in upper.columns if any(upper[column] > threshold)]
print('Colunas a considerar remover (correlacao):', to_drop_corr)

Typical output: Colunas a considerar remover (correlacao): ['X2', 'X4']. This is not a definitive order: choose based on predictive importance, relationship with the target y and interpretability.

Step 4: Compute Variance Inflation Factor (VIF)

VIF measures multivariate collinearity: the higher the VIF, the more a variable can be predicted by the rest. Common reference values: VIF > 5 => pay attention; VIF > 10 => strong collinearity. The calculation uses a regression of the variable of interest against all others.

from statsmodels.stats.outliers_influence import variance_inflation_factor

def compute_vif(df_input):
    X = df_input.values
    vif_data = pd.DataFrame()
    vif_data['feature'] = df_input.columns
    vif_data['VIF'] = [variance_inflation_factor(X, i) for i in range(X.shape[1])]
    return vif_data

vif_before = compute_vif(df)
print(vif_before)

Plausible example: X1 and X2 may show VIFs of 12 and 15 respectively, indicating they are mutually predictable and that action is warranted.

Step 5: Iterative removal of features by VIF

We remove the feature with the highest VIF repeatedly until all VIFs are below a threshold (e.g.: 5). This method addresses multivariate collinearity, not just pairs. Be careful: removing a variable can change the VIFs of the remaining ones; iteration ensures a stable solution.

def remove_high_vif(df_input, thresh=5.0):
    df_work = df_input.copy()
    while True:
        vif = compute_vif(df_work)
        max_vif = vif['VIF'].max()
        if max_vif <= thresh:
            break
        drop_feature = vif.sort_values('VIF', ascending=False)['feature'].iloc[0]
        df_work = df_work.drop(columns=[drop_feature])
        print('Removida por VIF:', drop_feature, 'VIF=', max_vif)
    return df_work

df_reduced_vif = remove_high_vif(df, thresh=5.0)
print('Colunas finais após VIF:', df_reduced_vif.columns.tolist())

In a typical example you may see removal of X2 and X4, leaving X1, X3, X5. Practical rule: if the removed variable has low interpretability cost and does not significantly reduce performance, removal is beneficial.

Step 6: Practical check with a model (example with LinearRegression)

Compare performance and coefficients before and after removal to understand the impact. We use cross_val_score for a simple evaluation. Ideally, perform feature selection inside cross-validation (pipeline) to avoid information leakage, but here we show a direct comparison to observe the effect.

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score

model = LinearRegression()
score_full = cross_val_score(model, df, y, cv=5, scoring='r2').mean()
score_reduced = cross_val_score(model, df_reduced_vif, y, cv=5, scoring='r2').mean()
print('R2 média (completo):', round(score_full, 4))
print('R2 média (reduzido):', round(score_reduced, 4))

Expected results: small differences. Plausible examples: R2 mean (full) = 0.72, R2 mean (reduced) = 0.71 — or even a slight improvement if removal reduces overfitting and coefficients become more stable.

Verify the outcome

Confirm that the columns listed for removal were indeed redundant by consulting corr and VIF. Good signs: VIFs below the threshold, reduction in the number of features without loss of performance or with slight improvement in R2, and more stable coefficients in the model. If performance drops considerably, reconsider the removal or opt for regularization (Ridge/Lasso) or dimensionality reduction (PCA).

Conclusion

Detecting and removing redundant features with correlation and VIF is a practical technique to simplify models and avoid collinearity. Next steps: test other approaches (PCA, Lasso/Ridge regularization, importance-based selection with RandomForest) and, very importantly, integrate selection into the cross-validation workflow to avoid optimism. Adjust thresholds according to the case and document which variables were removed and why — this facilitates auditing and reproducibility.