Alexandr  Semin
Alexandr Semin

Reputation: 1

How to specify best spline for this data

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47]
y = [31031.4,35241.7,42320.8,38146.7,38345.9,42320.8,33649.2,42883.3,35459,36371.6,23259.8,53740.6,36971.6,29518.3,45773,51421.43,56303.5,38786,31956.4,42717,43026.88,58479.4,50628.24,33375.19,40332.36,52731.29,48409.99,62328.65,48409.99,53941.38,52736.68,55794.38,48180.88,42949.35,48234.66,49505.83,50629.87,25361.3,57403.21,46805.93,55834.61,24978.13,51037.43,46727.27,31766.46,21553.01,34017.05,31533.17]
plt.plot(x, y, 'ro', ms=5)
spl = UnivariateSpline(x, y)
print(spl.get_knots())
xs = np.linspace(0, 47, 1000)
plt.plot(xs, spl(xs), 'g', lw=3)
#spl.set_smoothing_factor(1000000000)
#plt.plot(xs, spl(xs), 'b', lw=3)
plt.show()

I have the graphic where spline goes through the all points (screen 1), but I need the graphic like on screen 2.
Screen 1:

Screen 2:

Upvotes: 0

Views: 1129

Answers (1)

Jonas
Jonas

Reputation: 1847

UnivariateSpline has a smoothing parameter s, see here.

Positive smoothing factor used to choose the number of knots. Number of knots will be increased until the smoothing condition is satisfied:

sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) <= s

Since your y values are quite big your smoothing factor also has to be big (or you could normalize your data, see below).

spl = UnivariateSpline(x, y, s=1e9)

Looks like this:

enter image description here

Normalization:

spl = UnivariateSpline(x, y/np.max(y))
xs = np.linspace(0, 47, 1000)
plt.plot(xs, spl(xs)*np.max(y), 'g', lw=3)

Here s = len(w) (see link, w are the weights), which is the default. Plot:

enter image description here

spl = UnivariateSpline(x, y/np.max(y), s=float(len(y))*0.017)
xs = np.linspace(0, 47, 1000)
plt.plot(xs, spl(xs)*np.max(y), 'g', lw=3)

looks similar to your plot:

enter image description here

Upvotes: 1

Related Questions