【问题标题】:possible optimization in getting Minimum value indices from upper 2-dimensional matrix从上二维矩阵获取最小值索引的可能优化
【发布时间】:2020-12-05 05:34:28
【问题描述】:

嗨,谁能帮我优化从二维数组中获取最小值的函数,我只需要查看上三角矩阵或下三角矩阵。我有一个大小为 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

【问题讨论】:

    标签: python arrays python-3.x optimization


    【解决方案1】:

    您可以使用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 来获得更好的性能。

    【讨论】:

      猜你喜欢
      • 2015-09-26
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-06-30
      • 2014-05-22
      相关资源
      最近更新 更多