Skip to content
C.W.K.
Stream
Lesson 05 of 05 · published

When Linear Works and When It Breaks

~26 min · linear, limitations

Level 0Scout
0 XP0/48 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

Where linear models shine

Linear models are excellent when transformed feature effects combine roughly additively, the dataset is small to medium, interpretation matters, and the team needs a stable low-cost artifact. When performance is close, operational simplicity is a real feature.

Residuals reveal missed structure

Plot residuals against predictions and important features. Random scatter supports the additive approximation. Curves suggest nonlinear shape, fans suggest changing variance, and group-specific bands suggest a missing category or interaction. An average metric cannot expose those shapes.

When one feature's effect depends on another

Advertising may work differently by season, or discounts by customer tier. Add a small number of domain-supported interaction terms and validate them. Generating every pair creates quadratic growth and makes both estimation and explanation harder.

When the relationship bends or changes direction

Demand may fall as temperature rises and then climb again after a threshold. Bins, splines, or low-degree polynomials can express that shape. Check whether the transformation removes the residual pattern across folds; unconstrained polynomial expansion can turn dozens of inputs into tens of thousands of columns.

When error variance changes

Revenue and latency often show wider residuals at larger scales. Compare a log target, weighted regression, or quantile regression, then evaluate again in original units. Similar mean predictions can hide very different uncertainty for the cases that matter most.

When categories have too many values

Products or postal codes with thousands of values create a huge sparse one-hot matrix and difficult unseen categories. Compare leakage-safe target encoding, frequency encoding, hashing, or category-aware tree models, and verify that grouping rare values does not erase an important population.

The honest upgrade path

Repair transformations and a few justified interactions before abandoning the linear baseline. Then compare gradient-boosted trees on the identical split and metric. Include residual slices, latency, artifact size, and monitoring burden, and require a predeclared amount of durable lift. Upgrade because evidence pays for the complexity, not because the candidate is newer.

Code

Add explicit interaction features for linear models·python
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Ridge

pipe = Pipeline([
    ("poly", PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)),
    ("ridge", Ridge(alpha=1.0)),
])
When in doubt, try gradient boosting·python
import lightgbm as lgb

model = lgb.LGBMRegressor(n_estimators=500, learning_rate=0.05).fit(
    X_train, y_train, eval_set=[(X_val, y_val)], callbacks=[lgb.early_stopping(20)]
)

External links

Exercise

On your dataset, fit a Ridge model and a LightGBM regressor. Compare RMSE and the residual plots. If LightGBM wins by less than 5% RMSE, ship Ridge. Justify the call in three sentences.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Pippawarm

Comments 2

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.
  1. young-hoon Kim
    young-hoon Kim

    회귀분석 강의에서 반드시 짚고 넘어가야 할 함정 있잖아. 만약 데이터가 범죄발생수(target), 연도, 인구수, 교회수 라고 하자. 회귀 분석을 한다면 해당 데이터는 범죄발생수와 교회수의 증가가 밀접한 관계를 이루게 되고 결국 "교회수가 많을수록 범죄가 많다" 는 통계적으로 유의한 양(+)의 계수가 나올수가 있잖아, 이러한 모순을 필터링하는 단계가 있을까?

    💛 by Ttoriwarm💛 by Pippawarm
    1. Pippa
      Pippa· seriousyoung-hoon Kimyoung-hoon Kim

      네, 이건 회귀분석에서 아주 중요한 함정이에요. 자동으로 “모순 필터”가 따로 있는 건 아니고, 모델링 전에 범죄발생수를 인구 대비 비율로 바꾸고, 연도·인구·도시화 같은 공통 원인을 함께 통제한 뒤, 그래도 교회수 계수가 남는지 봐야 해요.

      핵심은 “통계적으로 유의하다”가 곧 “원인이다”는 뜻이 아니라는 점이에요. 이 예시는 오히려 상관관계와 인과관계를 구분하는 좋은 사례라서, regression quest 안에서도 꼭 한 번 다룰 만한 함정이에요.