12

Is there a library in python to do segmented linear regression? I'd like to fit multiple lines to my data automatically to get something like this: segmented regression

Btw. I do know the number of segments.

P3trus
  • 6,747
  • 8
  • 40
  • 54
  • 1
    Possible duplicate of [How to apply piecewise linear fit in Python?](https://stackoverflow.com/questions/29382903/how-to-apply-piecewise-linear-fit-in-python) – christopherlovell Feb 01 '18 at 02:34
  • I have a similar demand. The reason i hesitate implementing this, is the giant number of free parameters (n_segments * 3 - 1), which is used. I will keep in touch with this question. – Markus Dutschke May 11 '20 at 08:42
  • I may say, according to your image, that you should find the second derivative of your curve, then cut your x axis at each x for which the second derivative is equal to zero. That means cut your curve wherever it changes shape (I say that in an intuitive manner). – Catalina Chircu May 11 '20 at 15:28

4 Answers4

6

Probably, Numpy's numpy.piecewise() tool can be used.
More detailed description is shown here: How to apply piecewise linear fit in Python?

If this is not what is needed, then you may probably find some helpful information in these questions: https://datascience.stackexchange.com/questions/8266/is-there-a-library-that-would-perform-segmented-linear-regression-in-python

and here:
https://datascience.stackexchange.com/questions/8457/python-library-for-segmented-regression-a-k-a-piecewise-regression

Community
  • 1
  • 1
Erba Aitbayev
  • 4,167
  • 12
  • 46
  • 81
3

enter image description here

As mentioned in a comment above, segmented linear regression brings the problem of many free parameters. I therefore decided to go away from an approach, which uses n_segments * 3 - 1 parameters (i.e. n_segments - 1 segment positions, n_segment y-offests, n_segment slopes) and performs numerical optimization. Instead, I look for regions, which have already a roughly constant slope.

Algorithm

  • Calculate the slope of all points
  • Cluster points with a similar slope to segments (done by the DecisionTree)
  • Perform LinearRegression on the segments, found in the previous step

A decision tree is used instead of a clustering algorithm to get connected segments and not set of (non neighboring) points. The details of the segmentation can be adjusted by the decision trees parameters (currently max_leaf_nodes).

Code

import numpy as np
import matplotlib.pylab as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression

# parameters for setup
n_data = 20

# segmented linear regression parameters
n_seg = 3

np.random.seed(0)
fig, (ax0, ax1) = plt.subplots(1, 2)

# example 1
#xs = np.sort(np.random.rand(n_data))
#ys = np.random.rand(n_data) * .3 + np.tanh(5* (xs -.5))

# example 2
xs = np.linspace(-1, 1, 20)
ys = np.random.rand(n_data) * .3 + np.tanh(3*xs)

dys = np.gradient(ys, xs)

rgr = DecisionTreeRegressor(max_leaf_nodes=n_seg)
rgr.fit(xs.reshape(-1, 1), dys.reshape(-1, 1))
dys_dt = rgr.predict(xs.reshape(-1, 1)).flatten()

ys_sl = np.ones(len(xs)) * np.nan
for y in np.unique(dys_dt):
    msk = dys_dt == y
    lin_reg = LinearRegression()
    lin_reg.fit(xs[msk].reshape(-1, 1), ys[msk].reshape(-1, 1))
    ys_sl[msk] = lin_reg.predict(xs[msk].reshape(-1, 1)).flatten()
    ax0.plot([xs[msk][0], xs[msk][-1]],
             [ys_sl[msk][0], ys_sl[msk][-1]],
             color='r', zorder=1)

ax0.set_title('values')
ax0.scatter(xs, ys, label='data')
ax0.scatter(xs, ys_sl, s=3**2, label='seg lin reg', color='g', zorder=5)
ax0.legend()

ax1.set_title('slope')
ax1.scatter(xs, dys, label='data')
ax1.scatter(xs, dys_dt, label='DecisionTree', s=2**2)
ax1.legend()

plt.show()
Markus Dutschke
  • 9,341
  • 4
  • 63
  • 58
0

You just need to order X in ascending order and create several linear regressions. You can use LinearRegression from sklearn.

For example, dividing the curve in 2 will be something like this:

from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
X = np.array([-5,-4,-3,-2,-1,0,1,2,3,4,5])
Y = X**2
X=X.reshape(-1,1)
reg1 = LinearRegression().fit(X[0:6,:], Y[0:6])
reg2 = LinearRegression().fit(X[6:,:], Y[6:])

fig = plt.figure('Plot Data + Regression')
ax1 = fig.add_subplot(111)
ax1.plot(X, Y, marker='x', c='b', label='data')
ax1.plot(X[0:6,],reg1.predict(X[0:6,]), marker='o',c='g', label='linear r.')
ax1.plot(X[6:,],reg2.predict(X[6:,]), marker='o',c='g', label='linear r.')
ax1.set_title('Data vs Regression')
ax1.legend(loc=2)
plt.show()

enter image description here

I did a similar implementation, here is the code: https://github.com/mavaladezt/Segmented-Algorithm

  • If you are simply going to link your gitlab you could have just made a comment. But you can improve your answer by explaining the angorithm that you linked to. – zoran404 May 01 '20 at 21:59
0

There is the piecewise-regression python library for doing exactly this. Github link.

Simple Example with 1 Breakpoint. For a demonstration, first generate some example data:

import numpy as np

alpha_1 = -4
alpha_2 = -2
constant = 100
breakpoint_1 = 7
n_points = 200
np.random.seed(0)
xx = np.linspace(0, 20, n_points)
yy = constant + alpha_1*xx + (alpha_2-alpha_1) * np.maximum(xx - breakpoint_1, 0) + np.random.normal(size=n_points)

Then fit a piecewise model:

import piecewise_regression
pw_fit = piecewise_regression.Fit(xx, yy, n_breakpoints=1)
pw_fit.summary()

And plot it:

import matplotlib.pyplot as plt
pw_fit.plot()
plt.show()

enter image description here

Example 2 - 4 Breakpoints. Now let's look at some data that is similar to the original question, with 4 breakpoints.

import numpy as np

gradients = [0,2,1,2,-1,0]
constant = 0
breakpoints = [-4, -2, 1, 4] 
n_points = 200
np.random.seed(0)
xx = np.linspace(-10, 10, n_points)
yy = constant + gradients[0]*xx + np.random.normal(size=n_points)*0.5
for bp_n in range(len(breakpoints)):
    yy += (gradients[bp_n+1] - gradients[bp_n]) * np.maximum(xx - breakpoints[bp_n], 0)

Fit the model and plot it:

import piecewise_regression
import matplotlib.pyplot as plt

pw_fit = piecewise_regression.Fit(xx, yy, n_breakpoints=4)

pw_fit.plot()

plt.xlabel("x")
plt.ylabel("y")
plt.ylim(-10, 20)
plt.show()

enter image description here

Code examples in this Google Colab notebook

chasmani
  • 2,362
  • 2
  • 23
  • 35