我最近在性能方面遇到了障碍。我知道如何通过暴力破解/循环二维数组中的每一行和每一列来手动循环并从原始单元格到所有其他单元格进行插值。
但是,当我处理形状为 (3000, 3000) 的二维数组时,线性间距和插值会停止并严重影响性能。
我正在寻找一种可以优化此循环的方法,我知道矢量化和广播只是不确定如何在这种情况下应用它。
我会用代码和数字来解释
import numpy as np
from scipy.ndimage import map_coordinates
m = np.array([
[10,10,10,10,10,10],
[9,9,9,10,9,9],
[9,8,9,10,8,9],
[9,7,8,0,8,9],
[8,7,7,8,8,9],
[5,6,7,7,6,7]])
origin_row = 3
origin_col = 3
m_max = np.zeros(m.shape)
m_dist = np.zeros(m.shape)
rows, cols = m.shape
for col in range(cols):
for row in range(rows):
# Get spacing linear interpolation
x_plot = np.linspace(col, origin_col, 5)
y_plot = np.linspace(row, origin_row, 5)
# grab the interpolated line
interpolated_line = map_coordinates(m,
np.vstack((y_plot,
x_plot)),
order=1, mode='nearest')
m_max[row][col] = max(interpolated_line)
m_dist[row][col] = np.argmax(interpolated_line)
print(m)
print(m_max)
print(m_dist)
正如你所看到的,这是非常暴力的,我已经设法广播了这部分的所有代码,但卡在了这部分。这是我要实现的目标的说明,我将进行第一次迭代
1.) 输入数组
2.) 从 0,0 到原点 (3,3) 的第一个循环
3.) 这将返回 [10 9 9 8 0],最大值为 10,索引为 0
5.) 这是我使用的示例数组的输出
这是基于接受的答案的性能更新。