[英]interpolate missing values 2d python
我有一個二維數組(或矩陣,如果您願意),其中一些缺失值表示為NaN
。 缺失值通常位於一個軸上的條帶中,例如:
1 2 3 NaN 5
2 3 4 Nan 6
3 4 Nan Nan 7
4 5 Nan Nan 8
5 6 7 8 9
我想用一些合理的數字替換NaN
。
我研究了 delaunay 三角剖分,但發現的文檔很少。
我嘗試使用astropy
的卷積,因為它支持使用二維數組,而且非常簡單。 問題在於卷積不是插值,它會將所有值移向平均值(可以通過使用窄內核來緩解)。
這個問題應該是這個帖子的自然二維擴展。 有沒有辦法在二維數組中插入NaN
/缺失值?
是的,您可以使用scipy.interpolate.griddata
和掩碼數組,您可以使用參數method
選擇您喜歡的插值類型,通常'cubic'
做得很好:
import numpy as np
from scipy import interpolate
#Let's create some random data
array = np.random.random_integers(0,10,(10,10)).astype(float)
#values grater then 7 goes to np.nan
array[array>7] = np.nan
使用plt.imshow(array,interpolation='nearest')
看起來像這樣:
x = np.arange(0, array.shape[1])
y = np.arange(0, array.shape[0])
#mask invalid values
array = np.ma.masked_invalid(array)
xx, yy = np.meshgrid(x, y)
#get only the valid values
x1 = xx[~array.mask]
y1 = yy[~array.mask]
newarr = array[~array.mask]
GD1 = interpolate.griddata((x1, y1), newarr.ravel(),
(xx, yy),
method='cubic')
這是最終結果:
看看,如果 nan 值在邊緣並且被 nan 值包圍,則無法插入並保持nan
。 您可以使用fill_value
參數更改它。
這取決於您的數據類型,您必須進行一些測試。 例如,您可以故意屏蔽一些好的數據,嘗試使用具有屏蔽值的數組進行不同類型的插值,例如三次、線性等,並計算內插值與您之前屏蔽的原始值之間的差異,然后查看哪個方法返回您的細微差別。
你可以使用這樣的東西:
reference = array[3:6,3:6].copy()
array[3:6,3:6] = np.nan
method = ['linear', 'nearest', 'cubic']
for i in method:
GD1 = interpolate.griddata((x1, y1), newarr.ravel(),
(xx, yy),
method=i)
meandifference = np.mean(np.abs(reference - GD1[3:6,3:6]))
print ' %s interpolation difference: %s' %(i,meandifference )
這給出了這樣的東西:
linear interpolation difference: 4.88888888889
nearest interpolation difference: 4.11111111111
cubic interpolation difference: 5.99400137377
當然,這是針對隨機數的,因此結果可能會有很大差異是正常的。 因此,最好的辦法是對數據集的“故意屏蔽”部分進行測試,看看會發生什么。
為方便起見,這里有一個實現GM 答案的函數。
from scipy import interpolate
import numpy as np
def interpolate_missing_pixels(
image: np.ndarray,
mask: np.ndarray,
method: str = 'nearest',
fill_value: int = 0
):
"""
:param image: a 2D image
:param mask: a 2D boolean image, True indicates missing values
:param method: interpolation method, one of
'nearest', 'linear', 'cubic'.
:param fill_value: which value to use for filling up data outside the
convex hull of known pixel values.
Default is 0, Has no effect for 'nearest'.
:return: the image with missing values interpolated
"""
from scipy import interpolate
h, w = image.shape[:2]
xx, yy = np.meshgrid(np.arange(w), np.arange(h))
known_x = xx[~mask]
known_y = yy[~mask]
known_v = image[~mask]
missing_x = xx[mask]
missing_y = yy[mask]
interp_values = interpolate.griddata(
(known_x, known_y), known_v, (missing_x, missing_y),
method=method, fill_value=fill_value
)
interp_image = image.copy()
interp_image[missing_y, missing_x] = interp_values
return interp_image
我實際上會逐行手動檢查這個矩陣,每當你開始遇到一個 Nans 列表時,跟蹤緊接在 Nans 之前和緊接其后的數字,以及在返回普通數字之前看到的 Nans 的數量。 一旦找到這些數字,就可以自己用內插值覆蓋 Nans。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.