cjekel/piecewise_linear_fit_py
fit piecewise linear data for a specified number of line segments
What it solves
Data often isn't linear across its whole range. This library lets you fit a continuous piecewise linear function — that is, several connected straight lines — to your data, just by telling it how many line segments you want. It handles the tricky part of finding where the segments should break.
How it works
You provide the data and the number of line segments. The library uses global optimization (SciPy's differential evolution algorithm by default) to find the best locations for the breakpoints. Once those are known, it solves a least‑squares problem to get the coefficients for each line segment. There's also a faster fitfast() method that uses a multi‑start gradient optimization (L‑BFGS‑B) with Latin hypercube sampling for starting points. You can optionally supply known breakpoint locations, pass custom keywords to the optimizer, or use your own optimization routine with the objective function that minimizes the sum of squared residuals.
Who it's for
Anyone working with 1D data in Python who needs a simple, reliable way to model piecewise linear trends — for example, fitting sensor data, economic curves, or physical measurements where the relationship changes at certain thresholds. It's designed for users who don't want to manually choose breakpoints but still want control over the number of segments.
Highlights
- Specify only the number of line segments; breakpoints are found automatically
- Supports known breakpoint locations and custom optimization routines
- Includes a faster
fitfast()method using multi‑start gradient optimization - Now supports weighted fits and can also fit piecewise polynomials
- Installable via pip or conda, with documentation and examples
Related
- Project
- Project
- Project
- Project