Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Hoofdstuk 33 — Feature engineering, leakage‑valkuilen en model interpretatie (Permutation Importance, SHAP)

Let op: De tekst is in het Nederlands; alle Python codevoorbeelden zijn in het Engels.

Doelen:

  • Principes van feature engineering: interacties, niet‑lineariteit, datum/tijd features.
  • Dataleakage herkennen en voorkomen.
  • Modelinterpretatie met Permutation Importance; korte introductie tot SHAP.

Installatie:

pip install scikit-learn numpy pandas shap

Opmerking: shap kan extra afhankelijkheden vereisen en is soms traag; optioneel.

33.1 Feature engineering principes

  • Begin simpel; laat het model aangeven waar winst te behalen valt.
  • Gebruik PolynomialFeatures voor interacties/niet‑lineariteit in lineaire modellen.
  • Maak zinvolle domeinspecifieke features (ratio’s, aggregaties, datum‑extracties).
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

# Speeldata met niet‑lineariteit
df = pd.DataFrame({'x': range(100)})
df['y'] = 0.1*df['x']**2 - 2*df['x'] + 5
X = df[['x']]; y = df['y']

poly_model = Pipeline([
    ('poly', PolynomialFeatures(degree=2, include_bias=False)),
    ('lin', LinearRegression())
])
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=42)
poly_model.fit(X_tr, y_tr)
print('R^2 (test):', poly_model.score(X_te, y_te))

33.2 Leakage‑valkuilen

  • Imputers/scalers op de hele dataset fitten voor de split of buiten pipelines.
  • Doelfeatures die afgeleid zijn van y of informatie uit de toekomst (tijdreeksen).
  • Target encoding zonder CV‑schema.

Checklist:

  • Gebruik Pipelines en voer alle preprocessing binnen CV/splits uit.
  • Voor tijdreeksen: TimeSeriesSplit en alleen verleden gebruiken.

33.3 Permutation Importance

Permutation Importance meet de afname in performance wanneer een feature willekeurig wordt geschud.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.inspection import permutation_importance
import pandas as pd

X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('clf', LogisticRegression(max_iter=2000))
]).fit(X_train, y_train)

result = permutation_importance(pipe, X_test, y_test, scoring='roc_auc', n_repeats=10, random_state=42)
importances = pd.Series(result.importances_mean, index=X.columns).sort_values(ascending=False)
print(importances.head(10))

33.4 SHAP (kort)

import shap

# Voor lineaire/logistische modellen werkt KernelExplainer of LinearExplainer
explainer = shap.LinearExplainer(pipe.named_steps['clf'], shap.sample(X_train, 200))
shap_values = explainer.shap_values(shap.sample(X_test, 200))
shap.summary_plot(shap_values, shap.sample(X_test, 200), plot_type='bar')

Let op: SHAP vereist toegang tot onderliggende modelinvoer (na scaling/encoding); voor pipelines is extra werk nodig om getransformeerde features te reconstrueren.

33.5 Samenvatting

  • Feature engineering kan prestaties sterk beïnvloeden; voorkom lekken met correcte workflows.
  • Permutation Importance is model‑agnostisch en werkt goed met pipelines.
  • SHAP geeft gedetailleerde lokale en globale uitleg, maar kan zwaar zijn.