2016-09-07 2 views
-1

포인트는 [0, a] x [0, b] 평면과 모든 점에서 (x, y) \에 불규칙적으로 분포되어 있지만 약 80.000 포인트 (x, y, z)의 데이터 세트가 있습니다. x, y) 물리량 z는 일정한 값을 취한다. 그리드에서 보간하고자하는 데이터를 추가로 평가합니다.파이썬에서 비선형 그리드의 불규칙적으로 분산 된 데이터를 보간하는 방법은 무엇입니까?

이전에는 scipy.interpolate.griddata를 사용하여 정사각형, 2 차, 2 차원 그리드에서 성공적으로 보간했습니다. 그러나이 정규 그리드는 z의 변화가 극히 적은 영역을 적절하게 모델링 할 수없고, z를 약간만 변경 한 영역의 데이터 점이 많다는 단점이 있습니다.

z의 급격한 변화 영역에서 더 많은 격자 점과 z의 미세한 변화 영역에서 적은 데이터 점을 갖는 비선형 (바람직하게는 여전히 2 차, 그러나 가변적 인 메쉬 크기) 격자를 갖고 싶습니다.

답변

0

격자가 규칙적으로 될 수 있다고 생각하지만 각 격자 점은 동일한 샘플 수를 사용하여 평가되어야하므로 높은 샘플 밀도의 영역에서 강한 그라디언트 변화가 가능하며 데이터 희박 영역에서의 부드러움

나는 역 거리 가중 나무를 사용합니다. 내가 파이썬에서 주위에 떠있는 구현 :

class invdisttree(object): 
    """ 
    Compute the score of query points based on the scores of their k-nearest neighbours, 
    weighted by the inverse of their distances. 

    @reference: 
    https://en.wikipedia.org/wiki/Inverse_distance_weighting 

    Example: 
    -------- 

    import numpy as np 
    import matplotlib.pyplot as plt 
    from invdisttree import invdisttree 

    import matplotlib.pyplot as plt 

    # create sample points with structured scores 
    X1 = 10 * np.random.rand(1000, 2) -5 

    def func(x, y): 
     return np.sin(x**2 + y**2)/(x**2 + y**2) 

    z1 = func(X1[:,0], X1[:,1]) 

    # 'train' 
    tree = invdisttree(X1, z1) 

    # 'test' 
    spacing = np.linspace(-5., 5., 100) 
    X2 = np.meshgrid(spacing, spacing) 
    grid_shape = X2[0].shape 
    X2 = np.reshape(X2, (2, -1)).T 
    z2 = tree(X2) 

    fig, (ax1, ax2, ax3) = plt.subplots(1,3, sharex=True, sharey=True, figsize=(10,3)) 
    ax1.contourf(spacing, spacing, func(*np.meshgrid(spacing, spacing))) 
    ax1.set_title('Ground truth') 
    ax2.scatter(X1[:,0], X1[:,1], c=z1, linewidths=0) 
    ax2.set_title('Samples') 
    ax3.contourf(spacing, spacing, z2.reshape(grid_shape)) 
    ax3.set_title('Reconstruction') 
    plt.show() 

    """ 
    def __init__(self, X=None, z=None, leafsize=10): 
     if not X is None: 
      self.tree = cKDTree(X, leafsize=leafsize) 
     if not z is None: 
      self.z = z 

    def fit(self, X=None, z=None, leafsize=10): 
     """ 
     Arguments: 
     ---------- 
      X: (N, d) ndarray 
       Coordinates of N sample points in a d-dimensional space. 
      z: (N,) ndarray 
       Corresponding scores. 
      leafsize: int (default 10) 
       Leafsize of KD-tree data structure; 
       should be less than 20. 

     Returns: 
     -------- 
      invdisttree instance: object 
     """ 
     return self.__init__(X, z, leafsize) 

    def __call__(self, X, k=6, eps=1e-6, p=2, regularize_by=1e-9): 
     self.distances, self.idx = self.tree.query(X, k, eps=eps, p=p) 
     self.distances += regularize_by 
     weights = self.z[self.idx.ravel()].reshape(self.idx.shape) 
     mw = np.sum(weights/self.distances, axis=1)/np.sum(1./self.distances, axis=1) 
     return mw 

    def transform(self, X, k=6, p=2, eps=1e-6, regularize_by=1e-9): 
     """ 
     Arguments: 
     ---------- 
      X: (N, d) ndarray 
       Coordinates of N query points in a d-dimensional space. 

      k: int (default 6) 
       Number of nearest neighbours to use. 

      p: int or inf 
       Which Minkowski p-norm to use. 
       1 is the sum-of-absolute-values "Manhattan" distance 
       2 is the usual Euclidean distance 
       infinity is the maximum-coordinate-difference distance 

      eps: float (default 1e-6) 
       Return approximate nearest neighbors; the k-th returned value 
       is guaranteed to be no further than (1+eps) times the 
       distance to the real k-th nearest neighbor. 

      regularise_by: float (default 1e-9) 
       Regularise distances to prevent division by zero 
       for sample points with the same location as query points. 

     Returns: 
     -------- 
      z: (N,) ndarray 
       Corresponding scores. 
     """ 
     return self.__call__(X, k, eps, p, regularize_by) 
+0

답변 주셔서 감사 scipy.spatial 수입 cKDTree에서 NP 로 수입 NumPy와. 나는 얻지 못했습니다. 왜 모든 격자 점을 동일한 양의 점으로 평가하면이 경우에 도움이 될까요? 마지막으로 보간 된 데이터를 유한 차분 방정식 시스템에 넣고 싶습니다. 격자가 여전히 규칙적이라고 말했기 때문에, 이것이 유한 차분 방정식의 정확도를 향상시키는 방법을 보지 못했습니다 (근사치 임). 나는 데이터 포인트의 측면에서 볼 때 인구 밀도가 높거나 부족한 지역이 아니라는 것을 의미합니다. 그것은 보간하고 싶은 일부 지역의 물리량 z의 급격한 변화에 관한 것입니다. – Ben

+0

당신은 유한 차분 방정식에서 결과를 사용하고 싶다는 언급을하지 않았으므로이 질문은 순수하게 강한 그라디언트 변경을 국부적으로 맞추는 것이 었습니다 (가능한 경우). scipy.interpolate는 일반적으로 "전역"smoothness 매개 변수 (AFAIK; scipy.interpolate에서 구현을 검사하지 않았습니다)가있는 스플라인을 사용합니다. – Paul

+0

또한 메쉬 크기가 부드럽게 변하는 그리드는 사각형으로 만들 수 없습니다 ... 삼각형은보고있는 것입니다. – Paul

관련 문제