Editor

Polynomial vs Linear

Intermediate · Write the code · 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

The data below is curved (quadratic). Fit a plain LinearRegression and a polynomial regression (degree 2). Print two R2 scores (on training data) each rounded to 4 decimal places, on separate lines. Label them "Linear R2: ..." and "Poly R2: ...".

from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import r2_score
import numpy as np
np.random.seed(42)
X = np.random.uniform(-3, 3, 80).reshape(-1, 1)
y = 2 * X.flatten()**2 + np.random.normal(0, 2, 80)
# Fit linear model and print R2
# Fit polynomial model (degree 2) and print R2

More Linear Regression exercises

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