Module 12 · Scikit-learn: Building Real Models · Lesson 41 of 51
Trees, forests, cross-validation and tuning
Compare logistic regression, a decision tree, a random forest and gradient boosting with 5-fold cross-validation, tune with GridSearchCV, and read permutation importance.
In this lesson · about 50 minutes
- Estimate performance with k-fold cross-validation
- Tune hyperparameters with GridSearchCV without touching the test set
- Explain a model with permutation importance
Four models, five folds
Grid search
GridSearchCV tries every combination of the settings you list, cross-validates each, and keeps the best. Names inside a pipeline use a double underscore: model__max_depth. After searching, check the best model once on the test set.
grid = GridSearchCV(pipe, {"model__max_depth": [2, 4, 6], "model__min_samples_leaf": [5, 20]}, cv=5, scoring="roc_auc")
grid.fit(X_train, y_train)
grid.best_params_, grid.best_score_
What does the model use?
Permutation importance shuffles one feature at a time in the test data and measures how much the score drops. Big drop = the model relies on it. It works for any model, unlike tree-only "feature_importances_", which can favour features with many distinct values.
Exercise
Cross-validate a random forest
Build pipe: prep followed by RandomForestClassifier(n_estimators=100, min_samples_leaf=10, random_state=0). Using cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0), set cv_auc to the mean cross-validated ROC AUC on the training data, rounded to 3 decimals.
Code that runs before yours
import pandas as pd
import numpy as np
members = pd.read_csv("kc_members.csv")
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
num = ["age", "tenure_months", "visits_90d", "avg_spend", "app_user", "complaints"]
cat = ["home_branch", "plan"]
X, y = members[num + cat], members["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
prep = ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(handle_unknown="ignore"), cat)])
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.ensemble import RandomForestClassifierExercise
Tune a decision tree
Grid-search a DecisionTreeClassifier(random_state=0) inside a pipeline over max_depth in 2, 3, 4, 6 and min_samples_leaf in 5, 20, with cv=5 and scoring="roc_auc". Set best to grid.best_params_ and test_auc to the best model's test AUC rounded to 3 decimals.
Code that runs before yours
import pandas as pd
import numpy as np
members = pd.read_csv("kc_members.csv")
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
num = ["age", "tenure_months", "visits_90d", "avg_spend", "app_user", "complaints"]
cat = ["home_branch", "plan"]
X, y = members[num + cat], members["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
prep = ColumnTransformer([("num", StandardScaler(), num), ("cat", OneHotEncoder(handle_unknown="ignore"), cat)])
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_auc_scorePermutation importance
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.