0

What I am trying to do basically is translate this Matlab line:

slm = slmengine(x,y,'degree',1,'knots',numOfKnots,'plot','off');

to python.

So far I've found make_inter_spline which doesn't let me control how many knots there are, and make_lsq_spline which makes me calculate the knots before hand.

roydbt
  • 91
  • 1
  • 8
  • 1
    What is your ultimate goal? Are you trying to perform a piecewise linear fit like: https://stackoverflow.com/questions/29382903/how-to-apply-piecewise-linear-fit-in-python? – jared Jun 15 '23 at 17:43
  • @jared I am trying to fit a linear piecewise spline with less knots that data points – roydbt Jun 16 '23 at 08:55
  • So, does that link answer your question? You obviously would need to adjust it to fit your need of specifying the number of knots/bends. – jared Jun 16 '23 at 14:24
  • `pwlf` is doing what I am trying to do, but it is very slow. I have several thousand blobs, each containing hundreds of points. – roydbt Jun 16 '23 at 18:38
  • Can you provide a representative example to test on? – jared Jun 16 '23 at 18:48
  • I am trying to fit a 20-knot spline for every connected component in a binary image, for several thresholds – roydbt Jun 16 '23 at 18:57

2 Answers2

0

You could consider using scipy.interpolate.LSQUnivariateSpline (in at least 1.8.1). As noted in the documentation:

class scipy.interpolate.LSQUnivariateSpline(x, y, t, w=None, bbox=[None, None], k=3, ext=0, check_finite=False)

1-D spline with explicit internal knots.

Fits a spline y = spl(x) of degree k to the provided x, y data. t specifies the internal knots of the spline

Jon Custer
  • 686
  • 12
  • 17
  • But you must provide the knots before hand – roydbt Jun 16 '23 at 08:54
  • Well, either you know enough about what the spline is being fit to so you can provide reasonable knots, or you are asking the impossible. How much do you know about the points you are trying to run a spline through? – Jon Custer Jun 16 '23 at 15:11
  • I know the points should (but not always) be in a straight line, and that the spline should be in the middle of the blob of points – roydbt Jun 16 '23 at 18:39
0

I have found this package called pwlf that solves the problem, even though it is very slow compared to anything from SciPy. To use it you can simply do

spline = pwlf.PiecewiseLinFit(x, y)
spline.fitfast(num_of_knots)
y_hat = spline.predict(x)

which was exactly what I was looking for.

roydbt
  • 91
  • 1
  • 8