
Curved Data, Linear Model: Why Linear Regression Handles More Than Straight Lines
- كاتب موثّق
- scikit-learn 1.9
محتويات المقال
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
The name says "linear", and every introduction shows the same picture: a straight line through a cloud of points. With one raw feature, plain LinearRegressionreally 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.
What actually happens
"Linear" describes the weights
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.
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
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.034import numpy as npfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import cross_val_scorefrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import PolynomialFeatures, SplineTransformerrng = np.random.default_rng(0)temp = rng.uniform(-5, 40, 500).reshape(-1, 1) # daily temperature in Cdemand = 0.08 * (temp[:, 0] - 18) ** 2 + 50 + rng.normal(0, 3, 500)# Same LinearRegression, new features: temp and temp**2, or spline piecespoly = make_pipeline(PolynomialFeatures(degree=2), LinearRegression())spline = make_pipeline(SplineTransformer(), LinearRegression())forest = RandomForestRegressor(random_state=0) # a "different algorithm"for name, model in [("degree 2", poly), ("spline", spline), ("forest", forest)]: r2 = cross_val_score(model, temp, demand, cv=5).mean() print(f"{name:<9}R2 {r2:.3f}") # 0.949, 0.949, 0.926print(poly.fit(temp, demand)[-1].coef_.round(3)) # [ 0. -2.909 0.081]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?
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
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.
temp² scored 0.949 vs the forest's 0.926 | |
How to apply it in your project
Plot before you switch Plot 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. Transform inside a pipeline Put PolynomialFeaturesorSplineTransformerin amake_pipelinebefore the model, so cross-validation fits the transform on each training fold only.Compare on the same folds Score 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. Regularize as features grow Once you add many features, swap LinearRegressionforRidgeand tune itsalpha. The scikit-learn interpolation example pairs both transformers withRidge.Check what happens past your data Predict 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.
التعليقات (0)