i具有固定边界的二维晶格(L*l),并将N-S-W-E位点视为每个站点的4个邻居。每个站点都分配一个浮点值。对于每个站点,我正在计算其相邻站点的平均值添加到其自身价值中。我想使用scipy.signal的versolv2d解决此问题。以下是我的代码:
# 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)
我找不到将每个站点的相邻值总和除以其邻居的数量。
以以下方式我可以找到每个站点的邻居数量,但不知道如何将这些值纳入"结果"。有人可以建议我如何实现这一目标,或者在卷动中有更简单的内置方法2d吗?
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)
将一个数组除以另一个数组,逐元,使用 np.divide
:
np.divide(result, neighbours_count)
看起来这就是需要添加到您的代码中的全部;我认为这很好。
通常,要找到某种加权平均值,可以做以下操作:
- 在输入阵列上进行权重执行总和。
- 在与输入相同的大小的阵列上执行相同的操作。
- 将1的结果除以2。
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)