pwlf: Piecewise Linear Fitting

2.5.2 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import numpy as np
from pwlf import PiecewiseLinFit

# 1. Generate sample data
x = np.linspace(0, 10, 100)
y = 2 * x + np.random.normal(0, 0.5, 100) # First segment
y[50:] = -1 * x[50:] + 20 + np.random.normal(0, 0.5, 50) # Second segment

# 2. Initialize pwlf with your data
my_pwlf = PiecewiseLinFit(x, y)

# 3. Fit the function with a specified number of line segments (e.g., 2)
# The 'fit' method uses global optimization to find the best breakpoint locations.
breaks = my_pwlf.fit(2)
print(f"Optimal breakpoints: {breaks}")

# 4. Predict new y values using the fitted model
x_new = np.linspace(0, 10, 200)
y_predicted = my_pwlf.predict(x_new)

# You can also get other statistics after fitting
r_squared = my_pwlf.r_squared()
print(f"R-squared: {r_squared}")

# Example of getting slopes (after fit)
slopes = my_pwlf.slopes
print(f"Slopes of segments: {slopes}")

view raw JSON →