【问题标题】:Return 2-D array from scipy Regular Grid Interpolator从 scipy Regular Grid Interpolator 返回二维数组
【发布时间】:2017-06-16 22:49:55
【问题描述】:

我正在使用 Scipy 对 6 维数据进行插值,并且想要一种从我的插值器对象返回二维数组而不是一维数组的方法。目前,我只能通过使用 for 循环并多次调用插值器对象来实现这一点——我希望有更好的方法。

例如,在 3D 中:

#Random data
points=(np.arange(10), np.arange(5), np.arange(5))
values=np.random.rand(10, 5, 5)

interp_object=scipy.interpolate.RegularGridInterpolator(points, values)

我希望能够做到:

#Pick some points along each axis
x_points=np.arange(10)
y_points=[1.2, 3.1, 1.4, 4.8, 0.1]
z_points=3.5


xi=(x_points, y_points, z_points)

out_array=interp_object(xi)

但这会导致

ValueError: shape mismatch: objects cannot be broadcast to a single shape

我最终必须这样做:

out_array=np.empty((10, 5))
for i, y in enumerate(y_points):
    out_array[:, i]=interp_object((x_points, y, z_points))

这个循环是我代码中的主要瓶颈,如果可能的话,我想避免它!使用RegularGridInterpolator 或其他插值方法,我想做的是否可行?

【问题讨论】:

    标签: python arrays numpy scipy interpolation


    【解决方案1】:

    这部分代码:

    #Pick some points along each axis
    x_points=np.arange(10)
    y_points=[1.2, 3.1, 1.4, 4.8, 0.1]
    z_points=3.5
    
    xi=(x_points, y_points, z_points)
    
    out_array=interp_object(xi)
    

    将不起作用,因为您必须将输入作为您想要的所有点的数组提供。所以我们需要生成一个包含所有组合的矩阵。为此,我们可以使用meshgrid。我们还需要对数组维度进行一些操作以使一切正常,因此它可能看起来有点混乱。下面是一个例子:

    #Pick some points along each axis
    x_points = np.arange(9) + 0.5  # Points must be inside
    y_points = np.array([1.2, 3.1, 1.4, 3.9, 0.1])
    z_points = np.array([3.49])
    
    points = np.meshgrid(x_points, y_points, z_points)
    flat = np.array([m.flatten() for m in points])
    out_array = interp_object(flat.T)
    result = out_array.reshape(*points[0].shape)
    

    另外请注意,我已经稍微更改了您给出的分数。 RegularGridInterpolator 只能用于插值,超出创建插值函数时给出的范围将不起作用,本例中称为interp_object

    【讨论】:

    • 太好了,正是我想要的。谢谢!
    猜你喜欢
    • 2012-01-26
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多