Is there a Python equivalent to the smooth.spline function in R

前端 未结 3 1868
萌比男神i
萌比男神i 2021-02-07 07:06

The smooth.spline function in R allows a tradeoff between roughness (as defined by the integrated square of the second derivative) and fitting the points (as defined by summing

相关标签:
3条回答
  • 2021-02-07 07:32

    You can use R functions in Python with rpy2:

    import rpy2.robjects as robjects
    r_y = robjects.FloatVector(y_train)
    r_x = robjects.FloatVector(x_train)
    
    r_smooth_spline = robjects.r['smooth.spline'] #extract R function# run smoothing function
    spline1 = r_smooth_spline(x=r_x, y=r_y, spar=0.7)
    ySpline=np.array(robjects.r['predict'](spline1,robjects.FloatVector(x_smooth)).rx2('y'))
    plt.plot(x_smooth,ySpline)
    

    If you want to directly set lambda: spline1 = r_smooth_spline(x=r_x, y=r_y, lambda=42) doesn't work, because lambda has already another meaning in Python, but there is a solution: How to use the lambda argument of smooth.spline in RPy WITHOUT Python interprating it as lambda.

    To get the code running you first need to define the data x_train and y_train and you can define x_smooth=np.array(np.linspace(-3,5,1920)). if you want to plot it between -3 and 5 in Full-HD-resolution.

    0 讨论(0)
  • 2021-02-07 07:41

    I've been looking for exactly the same thing, but would rather not have to translate the code to Python. The Splinter package seems like an option, however: https://github.com/bgrimstad/splinter

    0 讨论(0)
  • 2021-02-07 07:49

    From research on google, I concluded that

    By contrast, the smooth.spline in R allows having knots at all the x values, without necessarily having a wiggly curve that hits all the points -- the penalty comes from the second derivative.

    0 讨论(0)
提交回复
热议问题