[英]Efficient way to calculate matrix cell distance from arbitrary coordinate in numpy
我正在寻找一种有效的 numpy 解决方案来解决以下问题:
我有一个 N x N numpy 矩阵。 给定矩阵的任意 i,j 坐标(可以是十进制)和任意范围,我需要计算矩阵的每个单元格的值除以其到指定范围内坐标的欧几里得距离。
如果不清楚。 给定坐标 (5.2, 5.5) 和 1 的范围。我需要取单元格 (5,5) 的所有 8 个邻居和单元格本身,并将这些单元格值除以它们到 (5.2, 5.5) 的距离。
下面是代码的一个简单的非常慢的版本。
PROXIMITY_RANGE = 1
x = 5.2
y = 5.5
min_x = int(max(int(x) - PROXIMITY_RANGE, 0))
max_x = int(min(int(x) + PROXIMITY_RANGE, IMAGE_SIZE - 1))
min_y = int(max(int(y) - PROXIMITY_RANGE, 0))
max_y = int(min(int(y) + PROXIMITY_RANGE, IMAGE_SIZE - 1))
total = 0
for c_x in np.arange(min_x, max_x+1):
for c_y in np.arange(min_y, max_y+1):
distance = math.sqrt((x - c_x)**2 + (y - c_y)**2)
total += input[c_y][c_x] / (1 + distance)
我们可以通过删除两个 for 循环并将它们替换为 numpy 操作和切片来矢量化您的代码以提高效率。 此外,删除标准 python math.sqrt
并将其替换为np.sqrt
应该会提高性能,对于较大的矩阵尤其明显
import numpy as np
IMAGE_SIZE = 100
input = np.random.randint(0, 100, size=(IMAGE_SIZE,IMAGE_SIZE))
PROXIMITY_RANGE = 1
x = 5.2
y = 5.5
min_x = int(max(int(x) - PROXIMITY_RANGE, 0))
max_x = int(min(int(x) + PROXIMITY_RANGE, IMAGE_SIZE - 1))
min_y = int(max(int(y) - PROXIMITY_RANGE, 0))
max_y = int(min(int(y) + PROXIMITY_RANGE, IMAGE_SIZE - 1))
size_y = max_y+1-min_y
size_x = max_x+1-min_x
#shape x and y to be like what you had in your for loops
y_vals = np.repeat(np.reshape(np.arange(min_y, max_y+1), (-1, size_y)), size_y, axis=0).transpose()
x_vals = np.tile(np.arange(min_x, max_x+1), (size_x, 1))
#extract the bits of the input we watn
sliced_input = input[min_y:max_y+1, min_x:max_x+1]
# compute euclidean distance
distance = np.sqrt((x_vals - x)**2 + (y_vals - y)**2) + 1
#sum the total of the cell values
total = np.sum(sliced_input / distance)
print(total)
此外,您有一个距离始终为零的错误。 这是由于在 for 循环迭代器中覆盖了x
和y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.