Editor

Fix the Scaling Bug

Intermediate · Fix the bug · from Build Your First ML Model: Linear Regression with scikit-learn

From the lesson: Build Your First ML Model: Linear Regression with scikit-learn

Imagine you're a real estate agent. A client asks, "How much is my house worth?" You look at the square footage, the number of bedrooms, and the neighborhood - then you give an estimate. You just did regression in your head.

Read the lesson

This code has a common data leakage bug. The scaler is fit on the full dataset before splitting. Fix it so the scaler is fit only on training data, then used to transform both train and test. Print the R2 score rounded to 4 decimal places.

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_regression
X, y = make_regression(n_samples=100, n_features=3,
noise=10, random_state=42)
# BUG: scaler is fit on ALL data (data leakage)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
print(round(model.score(X_test, y_test), 4))

More Linear Regression exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz