You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何同数据下SciPy LinearNDInterpolator与RegularGridInterpolator结果不同?

为什么SciPy的LinearNDInterpolator和RegularGridInterpolator在规则网格上插值结果不匹配?

我正在使用SciPy中的LinearNDInterpolator和RegularGridInterpolator函数对1D、2D及3D数据进行线性插值。我了解到两者的核心区别在于RegularGridInterpolator专为处理等间距或非等间距的规则(直线型)网格数据设计,且效率高于LinearNDInterpolator。但当我在均匀间距的规则网格上生成随机数据后,发现两者的插值结果并不匹配——由于网格规则且均采用线性插值,我原本预期结果相近。以下是我用于对比两种方法的代码:

import numpy as np
from scipy.interpolate import LinearNDInterpolator
from scipy.interpolate import RegularGridInterpolator
import matplotlib.pyplot as plt

#original data
x = np.linspace(0, 1, num=20)
y = np.linspace(1, 2, num=10)
X, Y = np.meshgrid(x, y)
values = np.random.rand(20, 10)
points = np.column_stack((X.flatten(), Y.flatten()))
values_flat = values.flatten()

#LinearNDInterpolation
interfunc = LinearNDInterpolator(points, values_flat)
x1 = np.linspace(0, 1, num=3000)
y1 = np.linspace(1, 2, num=3000)
X1, Y1 = np.meshgrid(x1, y1)
interpolated_values = interfunc(np.column_stack((X1.flatten(), Y1.flatten())))
interpolated_values = interpolated_values.reshape(X1.shape)
fig, ax = plt.subplots()
linear = ax.contourf(X1, Y1, interpolated_values.T)
fig.colorbar(linear, ax=ax)

#RegularGridInterpolation
fig2, ax2 = plt.subplots()
x2 = np.linspace(0, 1, num=3000)
y2 = np.linspace(1, 2, num=3000)
X2, Y2 = np.meshgrid(x2, y2)
points_grid = (x, y)
interfunc_grid = RegularGridInterpolator(points_grid, values, method="linear")
interpolated_values_grid = interfunc_grid(np.column_stack((X2.flatten(), Y2.flatten())))
interpolated_values_grid = interpolated_values_grid.reshape(X2.shape)
d = ax2.contourf(X2, Y2, interpolated_values_grid.T)
fig2.colorbar(d, ax=ax2)
plt.show()

你的代码存在维度匹配错误,这是导致两种插值结果不一致的核心原因:

  • meshgrid(x, y)生成的X和Y形状是(10, 20)(对应y的10个点、x的20个点),但你生成的values是(20, 10),两者形状完全不匹配。
  • 对于LinearNDInterpolator,X.flatten()和Y.flatten()按行优先(C顺序)展开点集,但values.flatten()是按(20,10)的行优先展开,直接导致点与对应的值完全错位。
  • 对于RegularGridInterpolator,参数points_grid=(x, y)要求values的形状为(len(y), len(x))即(10,20),你传入的(20,10)相当于把原始数据的轴转置,插值结果自然和LinearNDInterpolator的错误结果不匹配。

修正方法非常简单,只需让values的形状与网格一致:

values = np.random.rand(10, 20)  # 对应y的10个点,x的20个点

修正后,两种插值器的原始数据点值对应关系完全正确,在规则网格上的线性插值结果会完全一致(误差在浮点精度范围内)。

内容的提问来源于stack exchange,提问作者GGphys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:42:49