gpt4 book ai didi

r - 将 R 中稀疏矩阵的对角线归零的内存有效方法

转载 作者:行者123 更新时间:2023-12-04 09:16:33 25 4
gpt4 key购买 nike

我想将 R 中稀疏矩阵的对角线归零。我的蛮力方法是将其明确设置为零,但这似乎效率低下。有没有更有效的方法?

require(Matrix)
A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix")
diag(A) <- 0
A <- drop0(A) # cleaning up
澄清与解决:我最初的担心是 Matrix 会在对角线上使用实际零点来膨胀稀疏矩阵。事实证明并非如此(最终,尽管在此期间确实如此,请参阅下面的评论)。要看到这一点,请考虑如果我们将对角线设置为 1 会发生什么:
A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix")
format(object.size(A), units = "Mb")

[1] "38.3 Mb"

diag(A) <- 1
format(object.size(A), units = "Mb")

[1] "152.7 Mb"


我们添加的许多非零元素占用了 O(n) 内存,其中 n 是矩阵的维度。但是,与 diag(A) <- 0我们得到:
diag(A) <- 1
format(object.size(A), units = "Mb")

[1] "38.3 Mb"


也就是说,Matrix 已经有效地处理了这种情况。

最佳答案

您可以非常快速地找到非零条目:

ij <- which(A != 0, arr.ind = TRUE)

# Subset to those on the diagonal:

ij <- ij[ij[,1] == ij[,2],,drop = FALSE]

# And set those entries to zero:

A[ij] <- 0
编辑添加:
正如对原始问题的修订所说,这最终不会节省太多内存,但速度要快得多。 diag(A) <- 0在我的电脑上,语句大约需要 3.2 秒,而这 3 个步骤大约需要 0.2 秒。以下是如何进行计时:
library(microbenchmark)
microbenchmark(A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix"),
{A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix"); diag(A) <- 0},
{A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix");ij <- which(A != 0, arr.ind = TRUE);ij <- ij[ij[,1] == ij[,2],,drop = FALSE];A[ij] <- 0}, times = 10)
当我运行它时,我看到矩阵创建的中位时间为 137 毫秒,没有别的,创建时间为 3351 毫秒,加上 diag(A) 调用,创建时间为 319 毫秒,然后是我的代码。
它还在中间步骤中节省了大量内存,使用内存分析可以看出: Rprof(memory=TRUE); run code ; Rprof(NULL); summaryRprof() .

关于r - 将 R 中稀疏矩阵的对角线归零的内存有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63188681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com