3
2つの大きな疎行列(たとえばAとB)があります。私はゼロ以外の要素を0に置き換えたいと思います。は、すべての列にランクされたすべての要素のランクを含むB行列に基づいています。私の出力行列は、A行列の上位n個と下位n個の要素を含み、他のすべての非ゼロ値はゼロに等しくする必要があります。別のスパース行列に基づく疎行列のゼロ以外の値をゼロに置き換える最適化方法
以下は私のアプローチです。私は関数GetTopNBottomNでループを使用していますが、行列が大きくなると時間がかかるので、最適化できるかどうかは疑問です。私は非ゼロ要素のインデックスを抽出し、グループごとのランク
idx <- which(TestMatrix != 0, arr.ind=TRUE)
ranks = ave(-TestMatrix[idx], idx[,2], FUN=rank)
か、実際にご希望の結果を計算するためにave()
を使用
#input matrix
TestMatrix = Matrix(c(0.80,0.9,0.6,0,0,0.3,0.5,
0,0,0.3,0,0,0,0,
0.4,0.5,0.6,0,0,0.1,0,
0,0,0,0,0,0,0,
0.3,0.4,0.5,0.2,0.1,0.7,0.8,
0.6,0.7,0.5,0.8,0,0,0),7,sparse = TRUE)
#function to genrate ranks across all the columns for the input matrix
GenerateRankMatrix <- function(aMatrix){ ## Function Begins
n <- diff([email protected]) ## number of non-zeros per column
lst <- split([email protected], rep.int(1:ncol(aMatrix), n)) ## columns to list
r <- unlist(lapply(lapply(lst,function(x) x * -1), rank)) ## column-wise ranking and result collapsing
RankMatrix <- aMatrix ## copy sparse matrix
[email protected]x <- r ## replace non-zero elements with rank
return(RankMatrix)
} # Function Ends
## Function to retain Top N and Bottom N records
GetTopNBottomN <- function(aMatrix,rMatrix){
#aMatrix = original SparseMatrix, rMatrix = RankMatrix
n = 2 ## Top 2 and Bottom 2 Elements across all columns
for(j in 1:ncol(aMatrix)){
MaxValue = max(rMatrix[,j])
if(MaxValue <= 2 * n) next ##Ignore the column if there are less than or equal to 2*n nonzero values
for (i in 1: nrow(aMatrix)){
if(rMatrix[i,j] >n & rMatrix[i,j] <= MaxValue-n){ #IF Cond
aMatrix[i,j] = 0
} #IF ends
}
}
return(aMatrix)
}
#Output
RankMatrix = GenerateRankMatrix(TestMatrix) #Genrate Rank Matrix
#Output Matrix
GetTopNBottomN(TestMatrix,RankMatrix)