如何在 SciPy 中获得正确的插值?

How to get correct interpolated values in SciPy?

我正在使用 this data 通过 SciPy 的 InterpolatedUnivariateSpline 获得插值结果,但是当我用原始数据绘制插值数据时,它们似乎没有正确插值。我得到如图所示的插值数据:

如何使用此数据正确获取 Python 中的插值?

MWE

import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
import itertools


data = np.loadtxt('interp.dat', delimiter = '\t')
x = data[:, 0]
y = data[:, 1:]

x_interp = np.linspace(x[0], x[-1], 301)
y_interp = np.empty(shape = (x_interp.shape[0], y.shape[1]))
for i in range(y.shape[1]):
    f = interpolate.InterpolatedUnivariateSpline(x, y[:, i], k = 3)
    y_interp[:, i] = f(x_interp)


fig = plt.figure()
plot = plt.subplot(111)
markers = itertools.cycle(('o', '^', 's', 'v', 'h', '>', 'p', '<'))
for i in range (y.shape[1]):
    plt.plot(x, y[:, i], linestyle = '', marker = markers.next())
    plt.plot(x_interp, y_interp[:, i], linestyle = ':')
plot.set_ylim([0, 200])
plot.set_ylabel('Y')
plot.set_xlabel('X')
fig.savefig('interp.pdf')

问题是InterpolatedUnivariateSpline需要增加x点数,而你的点数正在减少。来自它的文档:

x : (N,) array_like Input dimension of data points -- must be increasing

如果您将 x- 值反转为

x = data[::-1, 0]
y = data[::-1, 1:]

而不是

x = data[:, 0]
y = data[:, 1:]

它插值正确。具有最高 y 值的数据仍然有些奇怪。

感谢您发布数据;否则就不可能找出问题所在。