pythonのパッケージscipyに、BSplineをデータから書いてくれるものがあった。
使う。
import numpy as np
from scipy.interpolate import make_interp_spline, BSpline
import matplotlib.pyplot as plt
rng = np.random.default_rng()
#x = np.linspace(-3, 3, 10)
N = 6
def f(x):
return x ** 2 / (1 + x) - x + 1 + np.sin(x / 2)
eps = rng.normal(0, 0.0001, N)
x = np.sort(np.array([0, 1, 2, 3, 4, 5]) + eps)
y = f(x) + 0.02 * rng.standard_normal(N)
xs = np.linspace(0, 4, 100)
print(x)
plt.plot(x, y, 'ro')
for k in [1, 2, 3, 6]:
spl_i = make_interp_spline(x, y, k=k)
plt.plot(xs, spl_i(xs), label=f'Interpolation spline (k={k})')
plt.plot(xs, f(xs), color = "red" ,label = "true")
plt.legend()
plt.show()
詳しいdocumentはこちら 。