🏋️ Übung: Die Werkstatt-Pipeline zu Ende bauen
Fülle die drei Lücken, damit das Fließband komplett ist: Scaler, Modell und Anzahl der Folds. Das Beispiel ist klein gehalten, damit du den Ablauf klar siehst.
📓 Öffne dein Jupyter Notebook oder Google Colab und probiere es selbst aus.
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({
"glucose": [85, 89, 90, 110, 120, 130, 145, 160, 170, 95],
"bmi": [23.1, 27.4, 31.0, 29.9, 34.2, 36.1, 32.8, 38.4, 35.7, 24.8],
"age": [21, 29, 33, 37, 40, 45, 50, 54, 60, 26],
"outcome": [0, 0, 0, 0, 1, 1, 1, 1, 1, 0]
})
X = df[["glucose", "bmi", "age"]]
y = df["outcome"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
pipe = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", ???),
("model", ???)
])
param_grid = {
"model__n_estimators": [100, 200],
"model__max_depth": [4, 8]
}
search = GridSearchCV(pipe, param_grid=param_grid, cv=???, scoring="roc_auc")
search.fit(X_train, y_train)
print(search.best_params_)
💡 Tipp anzeigen
Das Fließband soll hier aus Imputer, StandardScaler und RandomForest bestehen. Für die Werkstatt-Prüfung wollen wir fünf Probeessen.
✅ Lösung anzeigen
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({
"glucose": [85, 89, 90, 110, 120, 130, 145, 160, 170, 95],
"bmi": [23.1, 27.4, 31.0, 29.9, 34.2, 36.1, 32.8, 38.4, 35.7, 24.8],
"age": [21, 29, 33, 37, 40, 45, 50, 54, 60, 26],
"outcome": [0, 0, 0, 0, 1, 1, 1, 1, 1, 0]
})
X = df[["glucose", "bmi", "age"]]
y = df["outcome"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
pipe = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
("model", RandomForestClassifier(random_state=42))
])
param_grid = {
"model__n_estimators": [100, 200],
"model__max_depth": [4, 8]
}
search = GridSearchCV(pipe, param_grid=param_grid, cv=5, scoring="roc_auc")
search.fit(X_train, y_train)
print(search.best_params_)
Erwartete Ausgabe: ein Dictionary mit der besten Reglerkombination, zum Beispiel {"model__max_depth": 4, "model__n_estimators": 100}.