title: scipy linear spline fitting with predefined number of knots
body: <p>I try to fit a n knot linear splines to a set of points. 
  Now scipy have a method that fits polynomial of degree d (I set it to 1 for liner) to a set of points, but I cant define the number of knots I want (I can influence the number of knots via some constant parameter but I dont know it in advance, and search him with trail and error too expansive).
  I found a method that fits a curve to a set of points, it looked very promising at first.</p>
  
  <p>I tried to fit a linear spline with 3 knots, basicly the idea is to define a function that gets as parameter the location of the knots and the parameters of each line of the three.
  unfortunately I think it doesn't converges.</p>
  
  <p>I am looking for new Ideas on how to easily implement what I try to achieve.</p>
  
  <pre><code>import matplotlib.pyplot as plt
  
  def knot3_spline_wrapper(x,a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4):
      vfunc = np.vectorize(knot3_spline)
      return vfunc(x,a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4)
  
  def knot3_spline(x,a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4):
      if x &lt;c1:
          return x*a1+b1
      if c1&lt;=x &lt;c2:
          return x*a2+b2
      if c2&lt;=x&lt;c3:
          return x*a3+b3
      if c3&lt;=x:
          return x*a4+b4
  xdata = np.linspace(-2, 2, 50)
  y = np.power(xdata, 2)
  plt.plot(xdata, y, 'b-', label='data')
  popt, pcov = curve_fit(knot3_spline_wrapper, xdata, y)
  knot3_spline_wrapper(xdata, *popt)
  plt.plot(xdata, knot3_spline_wrapper(xdata, *popt), 'r-')
  </code></pre>
  
  <p>EDIT: I want to mention, I don't know nor want to specify knot positions...
  I want to find a way to find the "best" positions and the best lines that solve my problem</p>
  
  <p>result: <a href="https://i.stack.imgur.com/5qPZ7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5qPZ7.png" alt="enter image description here"></a></p>