I am porting a script written in R over to Python. In R I am using smooth.spline and in Python I am using SciPy UnivariateSpline. They don't produce the same results (even though they are both based on a cubic spline method). Is there a way, or an alternative to UnivariateSpline, to make the Python spline return the same spline as R?
I'm a mathematician. I understand the general idea of splines. But not the fine details of their implementation in Python or R.
Here is the code in R and then Python. The input data is the same for both.
Here is the input data:
x = 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0
y = -1, 1, 1, -1, 1, 0, .5, .5, .4, .5, -1
Here is the R code
x = seq(0,1, by = .1);
y = c(-1,1,1, -1,1,0, .5,.5,.4, .5, -1);
spline_xy = smooth.spline(x,y)
predict(spline_xy,x)
which outputs:
$x
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
$y
[1] 0.120614583 0.170800975 0.210954680 0.238032338 0.253672155
[6] 0.253684815 0.236432643 0.200264536 0.145403302 0.074993797
[11] -0.004853825
Here is the Python Code
import numpy as np
from scipy.interpolate import UnivariateSpline
x = np.linspace(0, 1, num = 11, endpoint=True)
y = np.array([-1,1,1, -1,1,0, .5,.5,.4, .5, -1])
spline_xy = UnivariateSpline(x,y)
print('x =', x)
print('ysplined =',spline_xy(x))
which outputs:
x = [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
ysplined =
[-0.26433566 -0.02587413 0.18857809 0.36585082 0.49277389
0.55617716 0.54289044 0.43974359 0.23356643 -0.08881119
-0.54055944]
I hoped the outputs, in R $y and in Python ysplined would be identical. But they aren't.
Any help, for example how to set the parameters, or explanations would be appreciated! Thank you in advance.