Piecewise linear regression from Javascript

The icu.stats object available to scripts can now do piecewise (segmented) linear regression. This is useful to automatically find thresholds or breakpoints in data for custom activity charts etc…

let x = [10, 20, ..., 15]
let y = [123, 130, ..., 189]
let r = icu.stats.piecewiseLinearRegression(x, y, 2)
console.log("r", r)

It returns a model for each segment that minimizes the total squared error across all models and the breakpoint positions. Note that your script is likely to exceed CPU time limits for 2 or more breakpoints and 500 data points.

Console output:

r breakpoints [50, 83] iterations 5672
segments[0] startIndex 0 endIndex 50 slope 0.01198272958667289 intercept 87.33066132487272 r2 0.2725313618257788
segments[1] startIndex 50 endIndex 83 slope -0.11776772580539199 intercept 106.820503128317 r2 0.9770982231206776
segments[2] startIndex 83 endIndex 111 slope -0.3254050093536113 intercept 151.9492520185915 r2 0.9963717388491345

The returned data structures are described below but the field names match that console output.

@Inigo_Tolosa

5 Likes

Hello @david. I’m not sure if, by mentioning me in this post, you’re implying that the implementation of any of my charts that use iterative linear regressions could exceed CPU limits, or if it’s just a general warning for anyone using the piecewiseLinearRegression method.

Not at all. I just thought you might be interested in this new feature given the charts you have built already.

1 Like

For sure. It’s really interesting and I’m sure I will find it very useful. Thanks!!

3 Likes