繁体   English   中英

检索 Julia 或 python 中矩阵的顺序删除列(也删除一行)的原始索引

[英]retrieve original index of sequentially removed column (a row is also removed) of an matrix in Julia or python

我想在删除前一个总和最大的列之后,在每次迭代中检索总和最大的列的原始索引。 同时,每次迭代时,删除列的相同索引的行也会从矩阵中删除。

例如,在 10 x 10 矩阵中,第 5 列的和最大,因此第 5 列和第 5 行被删除。 现在矩阵是 9 x 9 并且重新计算列的总和。 假设第 6 列的和最大,则当前矩阵的第 6 列和第 6 行被移除,即原始矩阵中的第 7 列。 反复执行此操作,直到保留所需的列数索引。

我在 Julia 中不起作用的代码粘贴在下面。 for 循环中的第二步是不正确的,因为每次迭代都会删除一行,因此列的总和不同。

谢谢!

# a matrix of random numbers
mat = rand(10, 10);
# column sum of the original matrix
matColSum = sum(mat, dims=1);

# iteratively remove columns with the largest sum
idxColRemoveList = [];
matTemp = mat;

for i in 1:4  # Suppose 4 columns need to be removed

    # 1. find the index of the column with the largest column sum at current iteration
    sumTemp = sum(matTemp, dims=1);
    maxSumTemp = maximum(sumTemp);
    idxColRemoveTemp = argmax(sumTemp)[2];
    
    # 2. record the orignial index of the removed scenario
    idxColRemoveOrig = findall(x->x==maxSumTemp, matColSum)[1][2];
    push!(idxColRemoveList, idxColRemoveOrig);
    
    # 3. update the matrix. Note that the corresponding row is also removed.
    matTemp = matTemp[Not(idxColRemoveTemp), Not(idxColRemoveTemp)];

end

python解决方案:

import numpy as np

mat = np.random.rand(5, 5)
n_remove = 3

original = np.arange(len(mat)).tolist()
removed = []

for i in range(n_remove):
    col_sum = np.sum(mat, axis=0)
    col_rm = np.argsort(col_sum)[-1]
    removed.append(original.pop(col_rm))
    mat = np.delete(np.delete(mat, col_rm, 0), col_rm, 1)

print(removed)
print(original)
print(mat)

我猜你遇到的问题是跟踪原始数组中当前列/行的索引是什么信息。 我刚刚使用了一个列表[0, 1, 2, ...] ,然后在每次迭代中弹出一个值。

对问题进行编码的一种更简单的方法是用非常小的数字替换所选列中的元素,而不是删除该列。 这种方法避免使用“排序”和“弹出”来提高代码效率。

import numpy as np

n = 1000
mat = np.random.rand(n, n)
n_remove = 500
removed = []

for i in range(n_remove):
    # get sum of each column
    col_sum = np.sum(mat, axis=0)
    col_rm = np.argmax(col_sum)
    # record the column ID
    removed.append(col_rm)
    
    # replace elements in the col_rm-th column and row with the zeros
    mat[:, col_rm] = 1e-10
    mat[col_rm, :] = 1e-10  
   
print(removed)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM