Bird
Raised Fist0
ML Pythonml~5 mins

Polynomial regression in ML Python

Choose your learning style10 modes available
Introduction

Polynomial regression helps us find curved lines that fit data better than straight lines. It models relationships that are not just straight but can bend.

When data points form a curve instead of a straight line.
To predict values that change in a non-linear way, like growth rates or temperature changes.
When simple linear regression does not fit the data well.
To capture patterns like U-shapes or hills in data.
When you want a simple model that can still handle curves.
Syntax
ML Python
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline

degree = 2
model = make_pipeline(PolynomialFeatures(degree), LinearRegression())
model.fit(X_train, y_train)
predictions = model.predict(X_test)

degree controls how curved the model is. Degree 1 means a straight line, degree 2 means a curve like a U or hill.

Using make_pipeline helps combine polynomial feature creation and linear regression in one step.

Examples
This creates a model that fits a quadratic curve (degree 2) to the data.
ML Python
model = make_pipeline(PolynomialFeatures(2), LinearRegression())
This fits a cubic curve (degree 3), which can bend more than degree 2.
ML Python
model = make_pipeline(PolynomialFeatures(3), LinearRegression())
Train the polynomial regression model and get predictions on new data.
ML Python
model.fit(X_train, y_train)
predictions = model.predict(X_test)
Sample Model

This example fits a polynomial regression model to data that follows y = x². It trains on the first 7 points and tests on the last 3. It prints predictions and how well the model fits.

ML Python
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.metrics import mean_squared_error, r2_score

# Sample data: X is input, y is output with a curve
X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
y = np.array([1, 4, 9, 16, 25, 36, 49, 64, 81, 100])  # y = x^2

# Split data into training and testing
X_train, X_test = X[:7], X[7:]
y_train, y_test = y[:7], y[7:]

# Create polynomial regression model with degree 2
model = make_pipeline(PolynomialFeatures(2), LinearRegression())

# Train the model
model.fit(X_train, y_train)

# Predict on test data
predictions = model.predict(X_test)

# Calculate metrics
mse = mean_squared_error(y_test, predictions)
r2 = r2_score(y_test, predictions)

# Print results
print("Predictions:", predictions)
print(f"Mean Squared Error: {mse:.2f}")
print(f"R2 Score: {r2:.2f}")
OutputSuccess
Important Notes

Choosing a very high degree can cause the model to fit noise, not just the pattern. This is called overfitting.

Polynomial regression is still a linear model but on transformed features (powers of inputs).

Always check model performance on test data to avoid overfitting.

Summary

Polynomial regression fits curved lines to data by adding powers of input features.

It is useful when data shows non-linear patterns like curves or hills.

Use PolynomialFeatures with LinearRegression to create the model easily.

Practice

(1/5)
1. What is the main purpose of polynomial regression in machine learning?
easy
A. To perform clustering on unlabeled data
B. To reduce the number of features in the dataset
C. To classify data into categories
D. To model non-linear relationships by adding powers of input features

Solution

  1. Step 1: Understand the goal of polynomial regression

    Polynomial regression extends linear regression by adding powers of input features to capture curves in data.
  2. Step 2: Compare options with this goal

    Only To model non-linear relationships by adding powers of input features describes modeling non-linear relationships by adding powers of features, which matches polynomial regression.
  3. Final Answer:

    To model non-linear relationships by adding powers of input features -> Option D
  4. Quick Check:

    Polynomial regression = model curves [OK]
Hint: Polynomial regression fits curves by adding powers of inputs [OK]
Common Mistakes:
  • Confusing polynomial regression with classification
  • Thinking it reduces features instead of expanding them
  • Mixing it up with clustering methods
2. Which Python code snippet correctly creates polynomial features of degree 3 using scikit-learn?
easy
A. from sklearn.linear_model import PolynomialFeatures poly = PolynomialFeatures(3) X_poly = poly.transform(X)
B. from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=3) X_poly = poly.fit_transform(X)
C. from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=2) X_poly = poly.fit(X)
D. from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=3) X_poly = poly.transform(X)

Solution

  1. Step 1: Check import and class usage

    PolynomialFeatures is in sklearn.preprocessing, so import must be from there.
  2. Step 2: Verify method calls and degree

    Degree=3 is correct. fit_transform(X) creates polynomial features properly. from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=3) X_poly = poly.fit_transform(X) matches all these.
  3. Final Answer:

    from sklearn.preprocessing import PolynomialFeatures poly = PolynomialFeatures(degree=3) X_poly = poly.fit_transform(X) -> Option B
  4. Quick Check:

    Correct import + degree + fit_transform = A [OK]
Hint: Use fit_transform with PolynomialFeatures from sklearn.preprocessing [OK]
Common Mistakes:
  • Importing PolynomialFeatures from wrong module
  • Using transform without fit first
  • Setting wrong degree value
3. Given this code, what will be the shape of X_poly if X has shape (5, 1) and degree=2?
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
medium
A. (5, 1)
B. (5, 2)
C. (5, 3)
D. (5, 4)

Solution

  1. Step 1: Understand PolynomialFeatures output shape

    For degree=2 and one feature, output includes [1, x, x^2], so 3 features total.
  2. Step 2: Calculate shape based on input rows and new features

    Input has 5 rows, so output shape is (5, 3).
  3. Final Answer:

    (5, 3) -> Option C
  4. Quick Check:

    Degree 2 with 1 feature = 3 columns [OK]
Hint: Output columns = combinations with degree + 1 for bias [OK]
Common Mistakes:
  • Forgetting the bias (constant 1) column
  • Assuming output shape equals input shape
  • Confusing degree with number of features
4. Identify the error in this polynomial regression code snippet:
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
poly = PolynomialFeatures(degree=2)
X_poly = poly.transform(X)
model = LinearRegression()
model.fit(X_poly, y)
medium
A. Using transform before fitting PolynomialFeatures
B. LinearRegression cannot be used with polynomial features
C. Missing import for LinearRegression
D. Degree should be 1 for polynomial regression

Solution

  1. Step 1: Check usage of PolynomialFeatures methods

    PolynomialFeatures must be fitted before transform; fit_transform fits and transforms in one step.
  2. Step 2: Identify the error in code

    Code calls poly.transform(X) without fitting first, causing error. Correct is poly.fit_transform(X).
  3. Final Answer:

    Using transform before fitting PolynomialFeatures -> Option A
  4. Quick Check:

    fit_transform needed before transform [OK]
Hint: Always fit PolynomialFeatures before transform or use fit_transform [OK]
Common Mistakes:
  • Calling transform without fit first
  • Thinking LinearRegression can't handle polynomial features
  • Ignoring method order in preprocessing
5. You have data with a clear curve pattern. You fit a polynomial regression model with degree 5 and get very low training error but high error on new data. What is the best next step?
hard
A. Reduce the polynomial degree to avoid overfitting
B. Increase the polynomial degree to 10 for better fit
C. Remove polynomial features and use linear regression only
D. Add more polynomial features of degree 6

Solution

  1. Step 1: Understand the problem of low training but high test error

    This indicates overfitting: model fits training data too closely but fails to generalize.
  2. Step 2: Choose a solution to reduce overfitting

    Reducing polynomial degree simplifies the model, helping it generalize better on new data.
  3. Final Answer:

    Reduce the polynomial degree to avoid overfitting -> Option A
  4. Quick Check:

    Overfitting? Lower degree polynomial [OK]
Hint: Lower degree to reduce overfitting when test error is high [OK]
Common Mistakes:
  • Increasing degree worsens overfitting
  • Removing polynomial features loses curve fit
  • Adding higher degree features increases complexity
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard