Scipy插值

插值是什麼？

``````import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
x = np.linspace(0, 4, 12)
y = np.cos(x**2/3+4)
print (x,y)``````

``````[ 0.          0.36363636  0.72727273  1.09090909  1.45454545  1.81818182
2.18181818  2.54545455  2.90909091  3.27272727  3.63636364  4.        ] [-0.65364362 -0.61966189 -0.51077021 -0.31047698 -0.00715476  0.37976236
0.76715099  0.99239518  0.85886263  0.27994201 -0.52586509 -0.99582185]``````

``````plt.plot(x, y,’o’)
plt.show()``````

一維插值

`scipy.interpolate`中的`interp1d`類是一種創建基於固定數據點的函數的便捷方法，可以使用線性插值在給定數據定義的域內的任意位置評估該函數。

``````f1 = interp1d(x, y,kind = 'linear')

f2 = interp1d(x, y, kind = 'cubic')``````

``````xnew = np.linspace(0, 4,30)

plt.plot(x, y, 'o', xnew, f1(xnew), '-', xnew, f2(xnew), '--')

plt.legend(['data', 'linear', 'cubic','nearest'], loc = 'best')

plt.show()``````

樣條曲線

``````import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
x = np.linspace(-3, 3, 50)
y = np.exp(-x**2) + 0.1 * np.random.randn(50)
plt.plot(x, y, 'ro', ms = 5)
plt.show()``````

``````spl = UnivariateSpline(x, y)
xs = np.linspace(-3, 3, 1000)
plt.plot(xs, spl(xs), 'g', lw = 3)
plt.show()``````

``````spl.set_smoothing_factor(0.5)
plt.plot(xs, spl(xs), 'b', lw = 3)
plt.show()``````