从上二维矩阵中获得最小值索引的可能优化



嗨,有人能帮我优化从二维数组中获取最小值的函数吗?我只能看到上下三角矩阵。我有一个大小为30000*30000的大数组,我必须找到最小值的索引。我还有一个掩码数组,我过去常常忽略某些行和列

def get_min_distance(self,data,min_ind2):
ind1=0
ind2=0
return_ind1=0
return_ind2=0
min_val=1000000
if min_ind2!=-1:
self.maskedArray[min_ind2]=1
for x in range(len(data)-1):
j=x+1
ind1=x
if self.maskedArray[x]==1:
pass
else:
min_max_array=ma.masked_array((data[x]),self.maskedArray
ind2=int(np.argmin(min_max_array[j:]))+j
if self.maskedArray[ind2]==1:
pass
else:
if min_val>data[ind1,ind2]:
min_val=data[ind1,ind2]
return_ind1=ind1
return_ind2=ind2
else:
pass
return return_ind1,return_ind2,min_val

您可以使用np.triu(data, k=1)data生成上三角矩阵。或者,可以使用np.tril(np.full(data.shape, val))生成一个填充有val的下三对角矩阵。此外,如果rowMaskcolMask都是布尔数组,则可以使用data[rowMask, :][:, colMask]过滤矩阵。最后,np.argmin取一个轴来选择在给定矩阵的所有行或列上迭代。如果未指定,则返回最小元素的展平索引。

你可以把它们混合在一起得到你想要的。这里有一个例子:

min_val = 1000000 # Better to set it to np.inf if the datatype if float32/float64
# Discard the lower-part of the matrix
triuData = np.triu(data, k=1) + np.tril(np.full(data.shape, min_val))
# Filter the lines and the columns
filteredData = triuData[rowMask, :][:, rowMask]
# Find the location of the minimum element in the filtered matrix
flattenMinId = np.argmin(filteredData)
return_ind1 = flattenMinId // filteredData.shape[1]
return_ind2 = flattenMinId % filteredData.shape[1]
# Reconstruct the index from the original data matrix
return_ind1 = np.where(np.cumsum(rowMask) == return_ind1)[0][0]
return_ind1 = np.where(np.cumsum(colMask) == return_ind2)[0][0]

由于临时矩阵的原因,此代码可能不是很有效。或者,您可以使用Numba的@njit来获得更好的性能。

最新更新