الانتقال إلى المحتوى
Machine LearningSupervised Learning· 6 دقائق للقراءة

Curved Data, Linear Model: Why Linear Regression Handles More Than Straight Lines

"Linear" describes the weights, not the shape. Give the same model curved features and it fits curves.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • scikit-learn 1.9
محتويات المقال

An analyst plots a city's daily electricity demand against temperature and sees a U: demand climbs on cold days for heating and on hot days for cooling. She fits LinearRegression, gets a slope of almost zero and a cross-validated score below zero, and writes in the ticket: "Linear regression can't do curves, moving to a neural network." The model wasn't the problem. Its inputs were.

The common misconception

Many developers believe linear regression can only model straight-line relationships, so curved data always needs a different algorithm. The belief is easy to come by:

  • The name says "linear", and every introduction shows the same picture: a straight line through a cloud of points.
  • With one raw feature, plain LinearRegression really does draw a straight line. That first experience sticks.
  • The formula ŷ = w₀ + w₁x₁ + … + wₚxₚ looks like a straight line (or a flat plane) in the inputs.

All three observations are true for the raw features. The mistake is assuming the model must use the raw features. Linear regression is linear in its weights, and you choose what those weights multiply.

What actually happens

The scikit-learn user guide defines linear models as methods where the target is expected to be a linear combination of the features. The word that matters is features: they can be anything you compute from the raw inputs.

"Linear" describes the weights

Take two inputs x₁ and x₂ and build new features from them: x₁, x₂, x₁x₂, x₁² and x₂². A model that learns one weight per new feature can fit a curved surface, yet the user guide points out that this is still a linear model: the prediction is linear in w, so the same solver fits it. Nothing about the algorithm changes; it just works in a bigger feature space.

That's what means here. PolynomialFeatures adds powers and products of your columns. SplineTransformer splits each feature's range into pieces joined at points called knots and adds a smooth curve segment per piece.

Same model, curved features

Here's the electricity story with synthetic data. Demand follows a U centered on 18 °C, plus noise. The score is : 1.0 is a perfect fit, 0.0 is what you'd get by always predicting the average, and below zero is worse than that.

Python
import numpy as npfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import cross_val_scorerng = np.random.default_rng(0)temp = rng.uniform(-5, 40, 500).reshape(-1, 1)  # daily temperature in C# Demand rises on cold days (heating) and on hot days (cooling)demand = 0.08 * (temp[:, 0] - 18) ** 2 + 50 + rng.normal(0, 3, 500)line = LinearRegression().fit(temp, demand)print(f"slope {line.coef_[0]:.4f}")  # slope -0.0019r2 = cross_val_score(LinearRegression(), temp, demand, cv=5).mean()print(f"R2 {r2:.3f}")  # R2 -0.034

The straight line prints a slope of -0.0019 and an R² of -0.034. Read literally, it says temperature doesn't affect demand, when temperature drives almost all of it. A line through a symmetric U is nearly flat, so its errors cancel out into "no effect".

Add one column, temp², and the same LinearRegression reaches 0.949. The cubic spline (scikit-learn's defaults: 5 knots, degree 3) matches it. A random forest, the "different algorithm", scores 0.926 on this data: switching models wasn't needed to fix the curve. And the weights stay readable. The data was generated from 0.08t² − 2.88t + 75.92, and the model learned 0.081 and -2.909.

Polynomials or splines?

Both are features for a linear model, but they behave differently at the edges. The preprocessing guide warns that polynomials oscillate near the boundaries, worse as the degree grows (Runge's phenomenon), and the interpolation example calls high powers particularly dangerous for extrapolating beyond the fitted range. Splines stay smooth, keep a low degree (usually 3), and let you control what happens past the last knot: by default they continue with a constant. One difference to remember: SplineTransformer treats each feature separately, so it won't create interaction terms such as x₁x₂. When two inputs only matter together, PolynomialFeatures with interaction_only=True adds just those products.

Curved boundaries in classification too

The same trick works for classifiers. The user guide's XOR example adds the product x₁x₂ as a feature, and a Perceptron, a linear classifier, then classifies all four points correctly. LogisticRegression works the same way: put the transformer in front of it in a pipeline and its decision boundary can curve.

MythReality
Linear regression only draws straight linesIt's linear in the weights; curved features give curved fits
Curved data needs a different algorithmHere, the same model with temp² scored 0.949 vs the forest's 0.926
A near-zero slope means no relationshipA line through a U is flat even when the effect is strong
Higher polynomial degree is always betterHigh degrees oscillate at the edges and extrapolate badly

How to apply it in your project

  1. Plot before you switchPlot the target against each important feature, or the residuals of your current linear model. A clear bend points to a feature problem, not an algorithm problem.
  2. Transform inside a pipelinePut PolynomialFeatures or SplineTransformer in a make_pipeline before the model, so cross-validation fits the transform on each training fold only.
  3. Compare on the same foldsScore the plain line, the transformed linear model and a tree model with the same cross-validation. Keep the simplest one that's close to the best.
  4. Regularize as features growOnce you add many features, swap LinearRegression for Ridge and tune its alpha. The scikit-learn interpolation example pairs both transformers with Ridge.
  5. Check what happens past your dataPredict a few values just beyond your training range. If the curve shoots off, prefer splines or clip inputs to the range you trained on.

Key takeaways

  • Linear regression is linear in its weights, not in the raw inputs.
  • Powers, products and spline pieces of a feature let the same model fit curves and stay interpretable.
  • A flat line through U-shaped data hides a strong effect; plot before concluding "no relationship".
  • Prefer low-degree splines over high-degree polynomials, and check behavior outside the training range.

📚 المصادر

  1. Linear Models: Polynomial regression, extending linear models with basis functions — scikit-learn User Guide
  2. Polynomial and Spline interpolation — scikit-learn examples
  3. Preprocessing data: Generating polynomial features — scikit-learn User Guide
  4. r2_score — scikit-learn API reference

التعليقات (0)