Skip to main content
 首页 » 编程设计

python之多个数组的 scipy 并行插值

2024年10月01日8tuyile006

我有多个相同维度的数组,或者更确切地说是一个矩阵

data.shape 
# (n, m) 

我想对 m 轴 进行插值并保留 n 轴。理想情况下,我会得到一个可以使用长度为 n 的 x-array 调用的函数。

interpolated(x) 
x.shape 
# (n,) 

我试过了

from scipy import interpolate 
interpolated = interpolate.interp1d(x=x_points, y=data) 
interpolated(x).shape 
# (n, n) 

但这会在给定点评估每个数组。有没有比丑陋的循环更好的方法呢

interpolated = array(interpolate.interp1d(x=x_points, y=array_) for 
                     array_ in data) 
array(func_(xi) for func_, xi in zip(interpolated, x)) 

请您参考如下方法:

正如您所说,(n,m) 形数据是 n 数据集的集合,每个数据集的长度为 m .您正在尝试向其传递一个 n 长度的 x 数组,并期望获得一个 n 长度的结果。也就是说,您在 n 个不相关点查询 n 个独立数据集。

这让我相信您需要使用 n 个独立的插值器。尝试通过对插值例程的单个调用来逃脱并没有真正的好处。据我所知,插值例程假定插值的目标是单个对象。要么是多元函数,要么是具有数组形状值的函数;在任何一种情况下,您都可以一次查询一个(可选的更高维)点的函数。例如,多线性插值适用于输入的行,因此(据我所知)没有办法“沿轴线性插值”。在你的情况下,你的 data 的行之间绝对没有关系,查询点之间也没有关系,因此在语义上也有动机为你的 n 使用独立的插值器问题。


为了方便起见,您可以将所有这些插值函数推到一个函数中以便于使用:

interpolated = [interpolate.interp1d(x=x_points, y=array_) for 
                     array_ in data] 
 
def common_interpolator(x): 
    '''interpolate n separate datasets at n separate input points''' 
    return array([fun(xx) for fun,xx in zip(interpolated,x)]) 

这将允许您使用长度为 n 的输入 array_like 对 common_interpolator 进行一次调用。

但由于您在评论中提到了它,如果查询指向此函数,您想要添加多个集合,您实际上可以使用 np.vectorize。这是一个包含三个简单虚拟函数的完整示例:

import numpy as np 
 
# three scalar (well, or vectorized) functions: 
funs = [lambda x,i=i: x+i for i in range(3)] 
 
# define a wrapper for calling them together 
def allfuns(xs): 
    '''bundled call to functions: n-length input to n-length output''' 
    return np.array([fun(x) for fun,x in zip(funs,xs)]) 
 
# define a vectorized version of the wrapper, (...,n) to (...,n)-shape 
allfuns_vector = np.vectorize(allfuns,signature='(n)->(n)') 
 
# print some examples 
x = np.arange(3) 
print([fun(xx) for fun,xx in zip(funs,x)]) 
# [0, 2, 4] 
print(allfuns(x)) 
# [0 2 4] 
print(allfuns_vector(x)) 
# [0 2 4] 
print(allfuns_vector([x,x+10])) 
#[[ 0  2  4] 
# [10 12 14]] 

如您所见,上述所有操作对于一维输入数组的工作方式相同。但是我们可以将一个 (k,n) 形状的数组传递给矢量化版本,它将按行执行插值,即每个 [:,n] 切片将被馈送到原始插值器束。据我所知,np.vectorize 本质上是 for 循环的包装器,但至少它使调用函数更加方便。