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

标签 python scipy interpolation

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

data.shape
# (n, m)

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

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 个独立的插值器。尝试通过一次插值例程调用来逃脱并没有真正的好处。据我所知,插值例程假设插值的目标是单个对象。多元函数或具有数组形状值的函数;在任何一种情况下,您都可以一次查询一个(可选更高维)点的函数。例如,多线性插值适用于输入的行,因此(再次据我所知)无法“沿轴线性插值”。在您的情况下,数据行之间绝对没有关系,查询点之间也没有关系,因此从语义上来说,为您的数据使用 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)])

这将允许您对 common_interpolator 进行一次调用,并输入长度为 narray_like

但是既然您在评论中提到了它,如果查询指向此函数,如果您想添加多个集合,实际上可以使用 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 循环的包装器,但至少它使调用函数更加方便。

关于python - scipy 多个数组的并行插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44634158/

相关文章:

python - 获得最大相干面积

c - 双线性插值图像调整大小标记 & 'splotches'

numpy 数组到 scipy.sparse 矩阵

python - 使用 scipy.interpolate.RegularGridInterpolator 出现错误 "There are 100 point arrays, but values has 2 dimensions"

r - 为缺失数据插入行并进行插值

python - 在Python中按特定值对JSON进行排序

python - Qt:尝试在 qt 中使用 python.h 时 undefined symbol

python - 如何在python函数中使用while循环?

python - 如何将主要刻度线显示为每个月的第一天,将次要刻度线显示为每天?

python - 使用 Python 进行并行精确矩阵对角化