cjekel / piecewise_linear_fit_py

fit piecewise linear data for a specified number of line segments
MIT License
289 stars 59 forks source link

Limit the slope of each segment of the curve #105

Open KXX-Change opened 1 year ago

KXX-Change commented 1 year ago

when find the best number of line segments,how to limit the slope of each segment? For example, make the slope of each segment in the final result less than 3.

cjekel commented 1 year ago

I don't have a nice way to do this, because the model parameters are fit with a least squares fit. The model parameters aren't the slope themselves, but the change in slope from the previous slopes.

That is not to say that this formulation is impossible.

It might be possible to write a constraint on the breakpoints such that the slope never hits 3 -- but I would think you would also want fits for known breakpoints where the slope never hits 3. These are two very different formulations.

Anyways, I just hacked up a constrained optimization problem that moves breakpoints such that the slope is less than a max_slope value. This still solve the least squares fit for given breakpoint locations. Take a look at https://github.com/cjekel/piecewise_linear_fit_py/blob/master/examples/slope_constraint_demo.ipynb and let me know if this works and if you have questions.