Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

Pipelines

~12 mincode completion

The scaling problem has a structural solution. A Pipeline chains preprocessing and a model into one object that behaves like a model:

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

pipe = Pipeline([
    ("scaler", StandardScaler()),
    ("model", LogisticRegression()),
])

pipe.fit(X_train, y_train)
pipe.predict(X_test)

Each step is a (name, object) pair. Every step except the last must have fit and transform; the last one only needs fit and predict.

The reason this matters is not tidiness. A pipeline makes leakage structurally impossible. pipe.fit fits the scaler on the training data only; pipe.predict applies that same scaler. There is no way to accidentally call fit_transform on your test set, because you never touch the scaler yourself.

It also means cross-validation does the right thing automatically: each fold refits the whole chain on that fold's training portion. Cross-validating a manually pre-scaled array leaks every fold's statistics into every other one, and that mistake is invisible in the score.

Your task:

Write build_and_score(X_train, y_train, X_test, y_test) that builds a StandardScaler plus LogisticRegression pipeline, fits it on the training data, and returns its accuracy on the test data as a float.

Pass random_state=0 to LogisticRegression so the result is reproducible.

Example Tests

A cleanly separable problem is classified perfectly

Input: {"X_test":[[0.5],[9.5]],"y_test":[0,1],"X_train":[[0],[1],[2],[8],[9],[10]],"y_train":[0,0,0,1,1,1]}

Expected: 1

Two features, still separable, still perfect

Input: {"X_test":[[0.5,0.5],[9.5,9.5]],"y_test":[0,1],"X_train":[[0,0],[1,1],[9,9],[10,10]],"y_train":[0,0,1,1]}

Expected: 1

Python
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

def build_and_score(X_train, y_train, X_test, y_test):
    """
    Build a scaler + classifier pipeline, fit it, and score it.

    Args:
        X_train, y_train: training data
        X_test, y_test: held-out data

    Returns:
        Accuracy on the test set, as a float.
    """
    # YOUR CODE HERE
    pass

Run your code to see results

⌘↵ runs against the visible tests

Loading docs…