How to fit more than one line to data points
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
If one straight line does not describe your data well, the next step is often not a higher-degree polynomial. A more interpretable option is to fit multiple line segments, usually called piecewise linear regression or segmented regression. The main decisions are where the breakpoints go and whether the segments must join continuously.
Start with the Statistical Question
"Fit more than one line" can mean different things:
- cluster the points into separate groups and fit one line per group
- fit contiguous line segments along the
xaxis - fit a continuous broken line with one or more change points
- fit a robust model that ignores outliers instead of adding more segments
The most common case is segmented regression: the data follows one slope up to a breakpoint and a different slope after it.
A simple continuous two-segment model can be written as:
- '
y = b0 + b1 * x + b2 * max(0, x - c)'
Here c is the breakpoint. Before c, the slope is b1. After c, the slope becomes b1 + b2.
A Practical Brute-Force Approach
If you only need one breakpoint, a very practical method is:
- sort points by
x - try each reasonable breakpoint candidate
- fit a left line and a right line
- choose the split with the smallest total squared error
That is simple, understandable, and often good enough.
Here is a runnable Python example using NumPy:
This does not enforce continuity at the breakpoint. It simply finds the best two separate linear fits over contiguous ranges.
Enforcing a Continuous Broken Line
If you want the two lines to meet, parameterize the model with a hinge term and optimize the breakpoint. One easy method is to scan possible c values and fit the linear coefficients with least squares.
This model is often easier to explain because the segments join smoothly.
More Than Two Lines
For more than one breakpoint, you can extend the same ideas, but model selection becomes important. More segments always reduce training error, so you need a criterion that balances fit quality against complexity.
Common choices are:
- cross-validation
- AIC or BIC
- a minimum number of points per segment
- domain knowledge about where regime changes can happen
If the data really contains several distinct trends, dynamic programming methods can find globally optimal segmented fits for a chosen number of segments. For many engineering tasks, though, one or two breakpoints plus validation is enough.
Common Pitfalls
A common mistake is adding segments when the real issue is outliers. In that case, robust regression may help more than piecewise regression.
Another mistake is fitting separate lines to unsorted data when the intent was segmented regression across the x axis. Segment order matters.
People also often choose too many breakpoints because training error keeps dropping. Without validation, that is just overfitting.
Finally, be explicit about whether continuity is required. Two independent lines and one continuous broken line are different models.
Summary
- Fitting more than one line usually means piecewise or segmented linear regression
- First decide whether you want separate clusters, contiguous segments, or a continuous broken line
- A brute-force split search is a practical method for fitting two segments
- A hinge-term model is useful when the segments should meet continuously
- Use validation or information criteria to avoid overfitting when adding breakpoints
- More lines are not always the right answer if the real problem is noise or outliers
Related reading
- How to fit the 2D scatter data with a line with C
- How to fix AttributeError module 'tensorflow' has no attribute 'get_default_graph'?
- How to fix error Cannot register 2 metrics with the same name /tensorflow/api/keras/optimizers
- How to fix error where a KerasTensor is passed to a TF API?
- How to fix initial_lr not specified when resuming optimizer error for scheduler?
- How to fix low volatile GPU-Util with Tensorflow-GPU and Keras?
- How to fix module 'tensorflow' has no attribute 'estimator' error
- How to fix ResourceExhaustedError OOM when allocating tensor
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.