Python 重复Scipy';网格数据
当数据集很多时,使用Scipy的griddata在不规则网格(x和y)中对数据(d)进行网格化是非常耗时的。但是,经纬度(x和y)总是相同的,只有数据(d)在变化。在这种情况下,一旦使用giddata,如何使用不同的d arry重复该过程以获得更快的结果Python 重复Scipy';网格数据,python,performance,numpy,scipy,Python,Performance,Numpy,Scipy,当数据集很多时,使用Scipy的griddata在不规则网格(x和y)中对数据(d)进行网格化是非常耗时的。但是,经纬度(x和y)总是相同的,只有数据(d)在变化。在这种情况下,一旦使用giddata,如何使用不同的d arry重复该过程以获得更快的结果 import numpy as np, matplotlib.pyplot as plt from scipy.interpolate import griddata x = np.array([110, 112, 114, 115, 119
import numpy as np, matplotlib.pyplot as plt
from scipy.interpolate import griddata
x = np.array([110, 112, 114, 115, 119, 120, 122, 124]).astype(float)
y = np.array([60, 61, 63, 67, 68, 70, 75, 81]).astype(float)
d = np.array([4, 6, 5, 3, 2, 1, 7, 9]).astype(float)
ulx, lrx = np.min(x), np.max(x)
uly, lry = np.max(y), np.min(y)
xi = np.linspace(ulx, lrx, 15)
yi = np.linspace(uly, lry, 15)
grided_data = griddata((x, y), d, (xi.reshape(1,-1), yi.reshape(-1,1)), method='nearest',fill_value=0)
plt.imshow(grided_data)
plt.show()
以上代码适用于一个d数组。
但是我还有数百个其他数组。
griddata
带有最近的最后使用最近的interpolator
。这是一个创建迭代器的类,用xi
调用迭代器:
elif method == 'nearest':
ip = NearestNDInterpolator(points, values, rescale=rescale)
return ip(xi)
因此,您可以创建自己的最接近Interpolator
,并使用不同的xi
多次调用它
但我认为在您的情况下,您需要更改值
。看看我看到的那个类的代码
self.tree = cKDTree(self.points)
self.values = y
\uuuu调用
执行以下操作:
dist, i = self.tree.query(xi)
return self.values[i]
我不知道创建树
与查询
的相对成本
因此,在使用\uuuu调用
之间更改值应该很容易。而且它看起来像是values
可以有多个列,因为它只是在第一维上建立索引
这个插值器非常简单,您可以使用相同的树思想编写自己的插值器
这里有一个最近的插值器,可以对相同的点重复插值,但不同的z
值。我还没有计时,看看它能节省多少时间
class MyNearest(interpolate.NearestNDInterpolator):
# normal interpolation, but returns the near neighbor indices as well
def __call__(self, *args):
xi = interpolate.interpnd._ndim_coords_from_arrays(args, ndim=self.points.shape[1])
xi = self._check_call_shape(xi)
xi = self._scale_x(xi)
dist, i = self.tree.query(xi)
return i, self.values[i]
def my_griddata(points, values, method='linear', fill_value=np.nan,
rescale=False):
points = interpolate.interpnd._ndim_coords_from_arrays(points)
if points.ndim < 2:
ndim = points.ndim
else:
ndim = points.shape[-1]
assert(ndim==2)
# simplified call for 2d 'nearest'
ip = MyNearest(points, values, rescale=rescale)
return ip # ip(xi) # return iterator, not values
ip = my_griddata((xreg, yreg), z, method='nearest',fill_value=0)
print(ip)
xi = (xi.reshape(1,-1), yi.reshape(-1,1))
I, data = ip(xi)
print(data.shape)
print(I.shape)
print(np.allclose(z[I],data))
z1 = xreg+yreg # new z data
data = z1[I] # should show diagonal color bars
您的想法可能更好,但我想先使用griddata创建空间,然后根据可用数据(d)填充空间。我错了吗?我粗略地设计了一个插值器,它可以让您通过索引获得正确形状的任何z
的最接近值。
z1 = np.array([xreg+yreg, xreg-yreg]).T
print(z1.shape) # (225,2)
data = z1[I]
print(data.shape) # (20,20,2)