pwlf is a Python library (v2.5.2) for fitting continuous piecewise linear functions to 1D data. It allows users to specify the number of line segments and uses global optimization (like differential evolution or L-BFGS-B) to find optimal breakpoint locations. The library also supports fitting with known breakpoints, constrained fits, and provides statistical properties like standard errors and R-squared values. It is actively maintained with regular releases.
pip install pwlfVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `pwlf` to fit a continuous piecewise linear function. It involves generating sample data, initializing the `PiecewiseLinFit` object, performing a fit for a specified number of line segments, and then predicting values from the fitted model. It also shows how to retrieve the optimal breakpoints and R-squared value.
If reproducibility with older `fitfast` results is critical, you must pin your `pwlf` version to `<2.5.0`. For new work, consider setting a `seed` when initializing `PiecewiseLinFit` for consistent results across runs.
Be aware that statistical outputs like standard errors might have slightly different values compared to `pwlf` versions prior to 2.1.0. Re-evaluate any critical results if upgrading from versions <2.1.0.
Upgrade your Python environment to 3.6 or newer to use current and future versions of `pwlf`. Alternatively, pin `pwlf` to `==2.0.4` if an older Python version is required.
Always ensure you have substantially more data points than the number of line segments you are trying to fit. Review your data and model complexity.
For reproducible results, initialize `pwlf.PiecewiseLinFit` with a `seed` argument, e.g., `my_pwlf = pwlf.PiecewiseLinFit(x, y, seed=123)`.
Ensure `bounds` is a list or tuple of `(lower_bound, upper_bound)` pairs, where the length of the list matches the number of breakpoints (which is `n_segments` for `fit` or `fitfast`). Example: `bounds=[(0.0, 5.0), (5.0, 10.0)]` for 2 segments with 1 breakpoint.
Check your data for sufficient variability and density. Reduce the number of line segments if you have sparse data. Adjust breakpoint bounds to be more flexible, or ensure there are enough data points within each segment.
Ensure that one of the `fit` methods is called and executed without errors before attempting to use any post-fitting analysis or prediction methods.
Update `pwlf` to the latest version (>=2.1.0), as this particular warning was addressed by changes in the `calc_slopes` logic during optimization. If the issue persists, review your data and initial breakpoint guesses/bounds to avoid nearly identical or problematic breakpoint locations.