【问题标题】:Scipy interpolate on structured 2d data, but evaluate at unstructured points?Scipy 在结构化二维数据上进行插值,但在非结构化点进行评估?
【发布时间】:2019-07-31 21:19:20
【问题描述】:

我有以下最少代码使用scipy.interpolate.interp2d 对二维网格数据进行插值。

import numpy as np
from scipy import interpolate
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx**2+yy**2)
f = interpolate.interp2d(x, y, z, kind='cubic')

现在f这里可以用来评价其他点了。问题是我要评估的点是完全随机的点,没有形成规则的网格。

# Evaluate at point (x_new, y_new), in total 256*256 points
x_new = np.random.random(256*256)
y_new = np.random.random(256*256)
func(x_new, y_new)

这会导致我的PC出现运行时错误,好像把x_new和y_new当成mesh grid,生成一个65536x65536的求值矩阵,这不是我的目的。

RuntimeError: Cannot produce output of size 65536x65536 (size too large)

完成工作的一种方法是逐个评估点,使用代码:

z_new = np.array([f(i, j) for i, j in zip(x_new, y_new)])

但是,它!!!

%timeit z_new = np.array([f(i, j) for i, j in zip(x_new, y_new)])

1.26 s ± 46.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

是否有任何更快的方法来评估随机点?

这里更快,我的意思是与下面的时间相当:

x_new = np.random.random(256)
y_new = np.random.random(256)

%timeit f(x_new, y_new)

相同的 256*256 = 65536 次评估,在我的 PC 中进行此操作的时间:

1.21 ms ± 39.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

不一定要和1.21ms的速度相当,121ms完全可以接受。

【问题讨论】:

    标签: python numpy scipy interpolation


    【解决方案1】:

    你要找的函数是scipy.interpolate.RegularGridInterpolator

    给定一组点 (x,y,z),其中 x 和 y 在规则网格上定义,它允许您对中间 (x,y) 点的 z 值进行采样。在您的情况下,这将如下所示

    import numpy as np
    from scipy import interpolate
    x = np.arange(-5.01, 5.01, 0.25)
    y = np.arange(-5.01, 5.01, 0.25)
    
    def f(x,y):
        return np.sin(x**2+y**2)
    
    z = f(*np.meshgrid(x, y, indexing='ij', sparse=True))
    func = interpolate.RegularGridInterpolator((x,y), z)
    
    x_new = np.random.random(256*256)
    y_new = np.random.random(256*256)
    xy_new = list(zip(x_new,y_new))
    z_new = func(xy_new)func(xy_new)
    

    更多详情请见https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.interpolate.RegularGridInterpolator.html

    【讨论】:

      猜你喜欢
      • 2016-06-08
      • 1970-01-01
      • 2021-08-20
      • 2011-11-02
      • 1970-01-01
      • 2011-06-26
      • 2019-12-10
      • 2011-03-10
      • 2015-10-09
      相关资源
      最近更新 更多