<p>可以使用自然三次平滑样条的<a href="https://github.com/espdev/csaps" rel="noreferrer">this numpy/scipy implementation</a>进行单变量/多变量数据平滑。平滑参数应在范围[0.0,1.0]内。如果我们使用等于1.0的平滑参数,我们就得到了没有数据平滑的自然三次样条插值。该实现还支持单变量数据的矢量化。</p>
<p>单变量示例:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import csaps
np.random.seed(1234)
x = np.linspace(-5., 5., 25)
y = np.exp(-(x/2.5)**2) + (np.random.rand(25) - 0.2) * 0.3
sp = csaps.UnivariateCubicSmoothingSpline(x, y, smooth=0.85)
xs = np.linspace(x[0], x[-1], 150)
ys = sp(xs)
plt.plot(x, y, 'o', xs, ys, '-')
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/vKBIk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vKBIk.png" alt="enter image description here"/></a></p>
<p>双变量示例:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import csaps
xdata = [np.linspace(-3, 3, 61), np.linspace(-3.5, 3.5, 51)]
i, j = np.meshgrid(*xdata, indexing='ij')
ydata = (3 * (1 - j)**2. * np.exp(-(j**2) - (i + 1)**2)
- 10 * (j / 5 - j**3 - i**5) * np.exp(-j**2 - i**2)
- 1 / 3 * np.exp(-(j + 1)**2 - i**2))
np.random.seed(12345)
noisy = ydata + (np.random.randn(*ydata.shape) * 0.75)
sp = csaps.MultivariateCubicSmoothingSpline(xdata, noisy, smooth=0.988)
ysmth = sp(xdata)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(j, i, noisy, linewidths=0.5, color='r')
ax.scatter(j, i, noisy, s=5, c='r')
ax.plot_surface(j, i, ysmth, linewidth=0, alpha=1.0)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/5HhGY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5HhGY.png" alt="enter image description here"/></a></p>