簡體   English   中英

將稀疏矩陣寫入R中的CSV

[英]Write a Sparse Matrix to a CSV in R

我有一個稀疏矩陣( dgCMatrix )作為擬合glmnet的結果。 我想將此結果寫入.csv但不能使用write.table()矩陣,因為它無法強制轉換為data.frame

有沒有辦法將稀疏矩陣強制轉換為data.frame或常規矩陣? 或者有沒有辦法將它寫入文件,同時保留可能是行名稱的系數名稱?

如果稀疏矩陣大小太大,那么將稀疏矩陣變換為正常矩陣將是危險的。 在我的情況下(文本分類任務),我得到了一個大小為22490×120,000的矩陣。 如果你嘗試獲得密集矩陣,我認為這將超過20 GB。 然后R會崩潰!

所以我的建議是,您可以簡單地以有效且內存友好的方式存儲稀疏矩陣,例如Matrix Market Format ,它保留所有非零值及其坐標(行和列號)。 在R中你可以使用writeMM方法

as.matrix()將轉換為完整的密集表示:

> as.matrix(Matrix(0, 3, 2))
     [,1] [,2]
[1,]    0    0
[2,]    0    0
[3,]    0    0

您可以使用write.csvwrite.table編寫結果對象。

直接轉換為密集矩陣可能會浪費大量內存。 R包Matrix允許使用summary()函數將稀疏矩陣轉換為內存有效的坐標三元組格式數據幀,然后可以輕松地將其寫入csv。 這可能比矩陣市場方法更簡單,更容易。 請參閱此相關問題的答案:將矩陣稀疏到R中的數據框

另外,這是Matrix包文檔中的插圖:

## very simple export - in triplet format - to text file:
data(CAex)
s.CA <- summary(CAex)
s.CA # shows  (i, j, x)  [columns of a data frame]
message("writing to ", outf <- tempfile())
write.table(s.CA, file = outf, row.names=FALSE)
## and read it back -- showing off  sparseMatrix():
str(dd <- read.table(outf, header=TRUE))
## has columns (i, j, x) -> we can use via do.call() as arguments to sparseMatrix():
mm <- do.call(sparseMatrix, dd)
stopifnot(all.equal(mm, CAex, tolerance=1e-15))
# input: a sparse matrix with named rows and columns (dimnames)
# returns: a data frame representing triplets (r, c, x) suitable for writing to a CSV file
sparse2triples <- function(m) {
 SM = summary(m)
 D1 = m@Dimnames[[1]][SM[,1]]
 D2 = m@Dimnames[[2]][SM[,2]]
 data.frame(row=D1, col=D2, x=m@x)
}

> library(Matrix)
> dn <- list(LETTERS[1:3], letters[1:5])
> m <- sparseMatrix(i = c(3,1,3,2,2,1), p= c(0:2, 4,4,6), x = 1:6, dimnames = dn)

> m
3 x 5 sparse Matrix of class "dgCMatrix"
  a b c d e
A . 2 . . 6
B . . 4 . 5
C 1 . 3 . .

> sparse2triples(m)
  row col x
1   C   a 1
2   A   b 2
3   B   c 4
4   C   c 3
5   A   e 6
6   B   e 5 

[編輯:使用data.frame]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM