问题描述
我需要在2d numpy数组中对某些Nan
值进行插值,例如,请参见下图:
I need to perform an interpolation of some Nan
values in a 2d numpy array, see for example the following picture:
在我目前的方法中,我使用scipy.interpolate.griddata
用于插值过程.但是我注意到在两个轴上镜像数组,即d2 = d[::-1, ::-1]
插值得出不同的结果.这是一个完整的示例:
In my current approach I use scipy.interpolate.griddata
for the interpolation procedure. However I noticed that whenmirroring the array on both axis i.e. d2 = d[::-1, ::-1]
the interpolation gives different results.Here is a complete example :
import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interp
def replace_outliers(f):
mask = np.isnan(f)
lx, ly = f.shape
x, y = np.mgrid[0:lx, 0:ly]
z = interp.griddata(np.array([x[~mask].ravel(),y[~mask].ravel()]).T,
f[~mask].ravel(),
(x,y), method='linear', fill_value=0)
return z
def main():
d = np.load('test.npy')
d2 = d[::-1, ::-1]
dn = replace_outliers(d)
dn2 = replace_outliers(d2)
print np.sum(dn - dn2[::-1, ::-1])
plt.imshow(dn-dn2[::-1, ::-1], interpolation='nearest')
plt.colorbar()
plt.show()
if __name__=='__main__':
main()
这给出了两个插值之间的差异:
This gives the difference between the two interpolations:
或np.sum
评估为-62.7
那么如何简单地对数组进行镜像在插值过程中给出不同的结果?我使用的坐标可能有问题吗?
So how can it be that a simple mirroring of the arraygives different results in the interpolation procedure?Is there maybe something wrong with the coordinates I use ?
推荐答案
原因很可能是线性插值基于基于三角形.但是,这种正方形网格对于Delaunay三角剖分来说是退化的情况,并且三角剖分并不是唯一的.我可以想象结果取决于数据点的顺序.
The reason likely is that the linear interpolation is triangle-based.However, such a square grid is a degenerate case for Delaunay triangulation, and the triangulation is not unique. I can imagine the outcome depends on the order of the data points.
对于丢失的数据点,我猜这两种情况对应于空白区域的不同三角剖分:
For a missing data point, I would guess the two cases correspond to different triangulations of the empty space:
A A
* * * *---*---* *---*---*
| / \ | | / | \ |
* * => D*-------*B or D* | *B
| \ / | | \ | / |
* * * *---*---* *---*---*
C C
如果现在计算中心的值,则从一个三角获得(B + D)/2,从另一个三角获得(A + C)/2.
If you now compute the value at the center, you get (B+D)/2 from one triangulation and (A+C)/2 from the other.
这篇关于使用scipy.interpolate.griddata进行2d插值的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!