dgCMatrix

Published by onesixx on

Compressed, sparse, column-oriented numeric matrices

sparse vector/matrix : 매우 크지만, 거의 모든 element가 0인 벡터/행렬

ex> 대부분은 행은 obs.이고, 열이 factor형태의 categorical변수인 데이터 행렬

> (m <- Matrix(c(0,0,2:0),3,5))      # matrix()가 아니라 Matrix()
> # m <- Matrix(c(0,0,2,1,0),nrow=3,ncol=5, byrow=F)
3 x 5 sparse Matrix of class "dgCMatrix"
              
[1,] . 1 . . 2
[2,] . . 2 . 1
[3,] 2 . 1 . .
> m %>% str
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:6] 2 0 1 2 0 1
  ..@ p       : int [1:6] 0 1 2 4 4 6
  ..@ Dim     : int [1:2] 3 5
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:6] 2 1 2 1 2 1
  ..@ factors : list()
> m[,1]
[1] 0 0 2

. (doc)은 0을 의미한다
모든 slot은 superclass인  "CsparseMatrix"(Sparse Matrices in Column-compressed Form)에서 상속받는다.
@i 는 nnzero (number of non-zero elements)가 위치하는 row의 number.
(row number는 0부터 시작, 즉 위 예에서 i의 범위는 0: (nrow(m)-1)
@p는 각 컬럼에서 nnzero의 마지막 index값
length(m@p)는 전체 컬럼개수 +1 즉, ncol(.) + 1 여기서 첫번째 p값은 0 이고 (p[1]==0 ),
마지막 p값은 nnzero의 마지막 인덱스값 p[length(p)] == nnzero
따라서 diff(m@p) 즉, diff(c(0,1,2,4,4,6), lag=1, differences=1)는 1 1 2 0 2 는 각 column의 nnzero 의 갯수.
@ Dim은 “sparseMatrix” (Mother of Sparse Matrices)에서 상속받는다.
@ Dimnames 는 class Matrix 에서 상속 받는다.
@x 는 0이 아닌 원소 (컬럼방향) = nnzero (number of non-zero elements)

> m <- Matrix(c(1,2,3,4,5,
                0,0,0,0,0,
                0,0,0,0,0), nrow=3, ncol=5, byrow=T)
3 x 5 sparse Matrix of class "dgCMatrix"
              
[1,] 1 2 3 4 5
[2,] . . . . .
[3,] . . . . .
> m %>% str
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:5] 0 0 0 0 0
  ..@ p       : int [1:6] 0 1 2 3 4 5
  ..@ Dim     : int [1:2] 3 5
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:5] 1 2 3 4 5
  ..@ factors : list()

Coercion of matrix to sparse matrix (dgCMatrix) and maintaining dimnames.

http://gallery.rcpp.org/articles/sparse-matrix-coercion/
https://github.com/imbs-hl/ranger/issues/135
library(ranger)
library(Matrix)
iris_sparse <- Matrix(data.matrix(iris), sparse = TRUE)
ranger(data = iris_sparse, dependent.variable.name = "Species", classification = TRUE)
Categories: Uncategorized

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x