Chapters
Python114 chapters

Exercises

Pipelines

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Chain a scaler and a logistic regression into one model, and print its accuracy.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=0, stratify=y
)
# build a pipeline, fit it, print the score rounded to three places
Exercise 2

The scaler is fitted outside the folds, which leaks. Put it inside a pipeline instead.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_breast_cancer(return_X_y=True)

leaked = StandardScaler().fit_transform(X)
scores = cross_val_score(LogisticRegression(max_iter=5000), leaked, y, cv=5)
print(round(scores.mean(), 3))
Exercise 3

Search three values of C on the pipeline, and print the best one.

Python needs scikit-learn, downloaded on first run
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_breast_cancer(return_X_y=True)
model = Pipeline([
    ("scale", StandardScaler()),
    ("classify", LogisticRegression(max_iter=5000)),
])
# search classify__C over 0.01, 1.0 and 100.0, then print the best