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

前端 未结 3 1867
萌比男神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.

提交回复
热议问题