0

我有 x 个样本和两组 y 个样本。我有一个数组 x 我想(1)当它的范围落在 x 样本的范围内时进行插值(2)当它大于 x 样本的最大值时外推(3)当它小于时填充零比 x 个样本的最小值。

现在,如果我只有一组 y 样本,我可以这样做

import numpy as np
from numpy.polynomial.polynomial import polyfit, polyval
from scipy.interpolate import interp1d

x_sample = np.arange(10, 50 + 1e-8, 5)
y_sample = x_sample * 2
x_large_id = 5 # extrapolate using the larger samples

interp = interp1d(x_sample, y_sample)
extrap = polyfit(x_sample[x_large_id:], y_sample[x_large_id:], 1)

x = np.arange(60)
y = np.zeros(60)
interp_id = (x > 10) & (x <= 50)
extrap_id = (x > 50)

y[interp_id] = interp(x[interp_id])
y[extrap_id] = polyval(x[extrap_id], extrap)

但是当我有两组 y 时,我不能这样做:

import numpy as np
from numpy.polynomial.polynomial import polyfit, polyval
from scipy.interpolate import interp1d

x_sample = np.arange(10, 50 + 1e-8, 5)
y_sample1 = x_sample * 2
y_sample2 = x_sample * 3
y_sample = np.stack([y_sample1, y_sample2], axis=0)
x_large_id = 5

interp = interp1d(x_sample, y_sample)
extrap = polyfit(x_sample[x_large_id:], y_sample[:, x_large_id:].swapaxes(0 , 1), 1)

x = np.arange(60)
y = np.zeros(2, 60)
interp_id = (x > 10) & (x <= 50)
extrap_id = (x > 50)

y[interp_id] = interp(x[interp_id])
y[extrap_id] = polyval(x[extrap_id], extrap)

我会得到TypeError: NumPy boolean array indexing assignment requires a 0 or 1-dimensional input, input has 2 dimensions。因为当我使用interp_id从数组中提取值时,它返回一个一维数组并且不保留维度的信息。

我可以像这样修复它

import numpy as np
from numpy.polynomial.polynomial import polyfit, polyval
from scipy.interpolate import interp1d

x_sample = np.arange(10, 50 + 1e-8, 5)
y_sample1 = x_sample * 2
y_sample2 = x_sample * 3
y_sample = np.stack([y_sample1, y_sample2], axis=0)
x_large_id = 5

interp = interp1d(x_sample, y_sample, bounds_error=False)
extrap = polyfit(x_sample[x_large_id:], y_sample[:, x_large_id:].swapaxes(0 , 1), 1)

x = np.arange(60)
x_ = np.stack([x, x], axis=0)
y = np.zeros((2, 60))

interp_id = (x_ > 10) & (x_ < 50)
extrap_id = (x_ >= 50)

y_interp = interp(x)
y_extrap = polyval(x, extrap)
y[interp_id] = y_interp[interp_id]
y[extrap_id] = y_extrap[extrap_id]

但是这样我会计算很多我实际上不需要的插值和外插点。这是不可取的,因为我正在处理的实际数据集非常大,而且我没有使用简单的 1d polyfit。所以我想知道是否有更有效的方法来做到这一点,这样我就可以(1)利用良好的矢量化和(2)不计算我不会使用的数据点(所以像这样的方法np.select不会有帮助)

4

0 回答 0