2016-12-22 59 views
1

我有一個固定邊界的2維網格(L * L),並將N-S-W-E網站視爲每個網站的4個鄰居。每個站點都分配一個浮點值。對於每個網站,我計算將其相鄰網站的值的平均值添加到其自己的值中。我想用scipy.signal中的convolv2d來解決這個問題。以下是我的代碼:使用convolve2d查找二維數組中的鄰居數量

# xi_out = constant1*xi + constant2*(sum of xi's neighbours)/no_of_xi's_neighbours 

import numpy as np 
from scipy.signal import convolve2d 

L = 6 # each side of 2D lattice 
a, b = (0.1, 0.5) # two constants 
arr = np.random.rand(L, L) # example 2D array 
# (3,3) window representing 4 neighbours which slides over 'arr' 
kernel = np.array([[0, b, 0], 
        [b, a, b], 
        [0, b, 0]]) 
neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) 
print(neighbors_sum) 

我無法找到一種方法來劃分每個站點的相鄰值的總和由其鄰居的數量。

通過以下方式,我可以找到每個網站的鄰居數量,但不知道如何將這些值合併到「結果」中。有人可以建議我怎麼做到,或者在convolve2d中有一個更簡單的內置方法來做到這一點?

arr = np.ones((L,L), dtype=np.int) 
kernel = np.array([[0, 1, 0], 
        [1, 0, 1], 
        [0, 1, 0]]) 
neighbors_count = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) 
print(neighbors_count) 

回答

0
import numpy as np 
from scipy.signal import convolve2d 

L = 6 
a, b = 0.1, 0.5 

arr = np.random.rand(L, L) 
arrb = arr.astype(bool) 
kernel = np.array([[0, 1, 0], 
        [1, 0, 1], 
        [0, 1, 0]]) 

neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0) 
neighbors_count = convolve2d(arrb, kernel, mode='same', boundary='fill', fillvalue=0) 
neighbors_mean = np.divide(neighbors_sum, neighbors_count) 
res = a * arr + b * neighbors_mean 
print(res) 
0

爲了通過另一個將一個陣列,元件逐元件,使用np.divide

np.divide(result, neighbours_count) 

看起來這是所有需要被添加到您的代碼;我認爲這是相當不錯的。

一般來說,找到某種加權平均,可以做到以下幾點:

  1. 與輸入陣列上的權重進行求和。
  2. 在與輸入大小相同的數組上執行同樣的操作。
  3. 鴻溝1由2
+0

你是正確的,除了結果的結果來實現這一點,我必須有一個共同的'採取'內核kernel' [1,1] = 0' ,以便將網站的價值本身從鄰居中排除。 – ajaydeep