Skip to content

API Reference

pwlreg

PWLReg: A flexible implementation of piecewise least squares regression.

AutoPiecewiseRegression

AutoPiecewiseRegression(
    n_segments,
    *,
    degree=1,
    continuity="c0",
    solver="auto",
    random_state=None
)

Bases: BaseEstimator, _BasePiecewiseRegressor

Piecewise linear regression with unknown breakpoint locations.

Parameters:

Name Type Description Default
n_segments int

The number of line segments to fit.

required
degree int | list[int]

The polynomial degree(s) of the line segments. If it is a single integer, all segments will have the same degree. If it is specified as a list, its length must be equal to n_segments. A degree of 0 will fit a constant (flat) line, 1 will fit a straight line, and 2 will fit a quadratic curve.

1
continuity str

The degree of continuity for the line segments at the breakpoints. The default of c0 means the segments will connect, but not necessarily smoothly (i.e. their derivatives may not be equal). None means the line segments can be fit completely separately from one another.

'c0'
solver str

The optimization routine to use in finding the breakpoints.

'auto'
random_state Any

Used in stochastic solvers for reproducibility.

None

Attributes:

Name Type Description
breakpoints_

Optimal breakpoint locations. The first and last elements will always be the min and max of the input data.

coef_

Vector coefficients that minimize the sum of squared errors.

ssr_

Sum of squared errors resulting from the fit.

n_params_

Number of estimated parameters.

n_iter

Number of iterations the solver needed to converge.

Initialize the auto regression object.

Source code in src/pwlreg/pwlreg.py
def __init__(
    self,
    n_segments: int,
    *,
    degree: int | list[int] = 1,
    continuity: str = "c0",
    solver: str = "auto",
    random_state: Any = None
) -> None:
    """Initialize the auto regression object."""
    self.n_segments = n_segments
    self.solver = solver
    self.random_state = random_state
    super().__init__(degree, continuity)

fit

fit(X, y, weights=None)

Fit piecewise regression model, finding optimal breakpoints.

Parameters:

Name Type Description Default
X ArrayLike

Input data

required
y ArrayLike

Target values

required
weights ArrayLike

Individual weights for each sample. If given a float, every sample will have the same weight.

None

Returns:

Type Description
AutoPiecewiseRegression

Fitted estimator.

Source code in src/pwlreg/pwlreg.py
def fit(
    self, X: npt.ArrayLike, y: npt.ArrayLike, weights: npt.ArrayLike = None
) -> "AutoPiecewiseRegression":
    """Fit piecewise regression model, finding optimal breakpoints.

    Args:
        X: Input data
        y: Target values
        weights: Individual weights for each sample. If given a float, every
            sample will have the same weight.

    Returns:
        Fitted estimator.
    """
    random_state_ = check_random_state(self.random_state)
    X, y = check_X_y(X, y, accept_sparse=True, ensure_2d=False, y_numeric=True)
    weights = _check_sample_weight(weights, X, dtype=X.dtype)

    if self.n_segments == 1:
        self.breakpoints_ = np.array([np.min(X), np.max(X)])
        return self.fit_with_breaks(X, y, self.breakpoints_, weights)

    self.breakpoints_, self.n_iter = _auto_piecewise_regression(
        X,
        y,
        self.n_segments,
        self.degree,
        self.continuity,
        weights,
        solver=self.solver,
        random_state=random_state_,
        return_n_iter=True,
    )

    return self.fit_with_breaks(X, y, self.breakpoints_)

predict

predict(X)

Predict using the fitted piecewise regression model with optimal breakpoints.

Parameters:

Name Type Description Default
X ArrayLike

Input data

required

Returns:

Type Description
ArrayLike

Predicted values

Source code in src/pwlreg/pwlreg.py
def predict(self, X: npt.ArrayLike) -> npt.ArrayLike:
    """Predict using the fitted piecewise regression model with optimal breakpoints.

    Args:
        X: Input data

    Returns:
        Predicted values
    """
    return self._decision_function(X, self.breakpoints_)

PiecewiseLinearRegression

PiecewiseLinearRegression(
    *, breakpoints=None, degree=1, continuity="c0"
)

Bases: BaseEstimator, _BasePiecewiseRegressor

Piecewise linear regression with known breakpoint locations.

Parameters:

Name Type Description Default
breakpoints ArrayLike

Array of breakpoint locations. Must include the minimum and maximum points of your input data. If None, it is assumed to be the min and max of the input data with no points in between. This will result in a single line segment being fit to the data.

None
degree int | list[int]

The polynomial degree(s) of the line segments. If it is a single integer, all segments will have the same degree. If it is specified as a list, its length must be one less than the number of breakpoints. A degree of 0 will fit a constant (flat) line, 1 will fit a straight line, and 2 will fit a quadratic curve.

1
continuity str

The degree of continuity for the line segments at the breakpoints. The default of c0 means the segments will connect, but not necessarily smoothly (i.e. their derivatives may not be equal). None means the line segments can be fit completely separately from one another.

'c0'

Attributes:

Name Type Description
coef_

Vector coefficients that minimize the sum of squared errors.

ssr_

Sum of squared errors resulting from the fit.

n_params_

Number of estimated parameters.

Initialize the regression object.

Source code in src/pwlreg/pwlreg.py
def __init__(
    self,
    *,
    breakpoints: npt.ArrayLike = None,
    degree: int | list[int] = 1,
    continuity: str = "c0"
) -> None:
    """Initialize the regression object."""
    self.breakpoints = breakpoints
    super().__init__(degree, continuity)

fit

fit(X, y, *, weights=None)

Fit piecewise regression model.

Parameters:

Name Type Description Default
X ArrayLike

Input data

required
y ArrayLike

Target values

required
weights ArrayLike

Individual weights for each sample. If given a float, every sample will have the same weight.

None

Returns:

Type Description
PiecewiseLinearRegression

Fitted estimator.

Source code in src/pwlreg/pwlreg.py
def fit(
    self, X: npt.ArrayLike, y: npt.ArrayLike, *, weights: npt.ArrayLike = None
) -> "PiecewiseLinearRegression":
    """Fit piecewise regression model.

    Args:
        X: Input data
        y: Target values
        weights: Individual weights for each sample. If given a float, every
            sample will have the same weight.

    Returns:
        Fitted estimator.
    """
    X, y = check_X_y(X, y, accept_sparse=True, ensure_2d=False, y_numeric=True)
    weights = _check_sample_weight(weights, X, dtype=X.dtype)

    if self.breakpoints is None:
        self.breakpoints = np.array([np.min(X), np.max(X)])

    self.fit_with_breaks(X, y, self.breakpoints, weights)
    return self

predict

predict(X)

Predict using the fitted piecewise regression model.

Parameters:

Name Type Description Default
X ArrayLike

Input data

required

Returns:

Type Description
ArrayLike

Predicted values

Source code in src/pwlreg/pwlreg.py
def predict(self, X: npt.ArrayLike) -> npt.ArrayLike:
    """Predict using the fitted piecewise regression model.

    Args:
        X: Input data

    Returns:
        Predicted values
    """
    return self._decision_function(X, self.breakpoints)