稀疏矩阵存储格式CSC(Compressed Sparse Columns Format)
最近在看XGBoost的论文,其中提到为了并行学习,我们使用了Column Block的这种方法[1],而每个Block中的数据,我们就是以CSC形式存储的。本文根据网络内容重新整理,介绍下CSC这种格式。主要参考自理解Compressed Sparse Column Format (CSC)目的CSC的目的就是用来压缩矩阵,主要是使用一些信息来表示矩阵中非0元素存储的位置。Spark
·
最近在看XGBoost的论文,其中提到为了并行学习,我们使用了Column Block的这种方法[1],而每个Block中的数据,我们就是以CSC形式存储的。本文根据网络内容重新整理,介绍下CSC这种格式。主要参考自理解Compressed Sparse Column Format (CSC)
目的
CSC的目的就是用来压缩矩阵,主要是使用一些信息来表示矩阵中非0元素存储的位置。
Spark API
package org.apache.spark.ml.linalg
/**
* Creates a column-major sparse matrix in Compressed Sparse Column (CSC) format.
* @param numRows, number of rows
* @param numCols, number of columns
* @param colPtrs, the index corresponding to the start of a new column
* @param rowIndices, the row index of the entry
* @param values, non-zero matrix entries in column major
*/
@Since("2.0.0")
def sparse(
numRows: Int,
numCols: Int,
colPtrs: Array[Int],
rowIndices: Array[Int],
values: Array[Double]): Matrix = {
new SparseMatrix(numRows, numCols, colPtrs, rowIndices, values)
}
其中,主要是第三个参数不容易理解,下面举例说明。
# 矩阵如下
1 0 4
0 3 5
2 0 6
我们可以这样创建上边矩阵的CSC格式。
import org.apache.spark.ml.linalg.{Matrix, Matrices}
val sm: Matrix = Matrices.sparse(3, 3, Array(0,2,3,6), Array(0,2,1,0,1,2), Array(1.0, 2.0, 3.0, 4.0, 5.0, 6.0))
// 输出如下
// (行,列) 值
(0,0) 1.0
(2,0) 2.0
(1,1) 3.0
(0,2) 4.0
(1,2) 5.0
(2,2) 6.0
可以看到,矩阵和前述是一致的,那么第三个参数是并不是列索引,那么是什么意思?
总结:
总结:
- Array中元素的个数是矩阵的列数+1。
- Array元素肯定是0。第二个元素是第一列的非零元素的数量
- 后续的值为(前一个值 + 下一列非零元素的数量)
当然我们也可以根据CSC格式的矩阵反着推出其原本形式。CSC比普通的根据行列索引定位非零值节省更多的空间,还有更多的好处望指教。
Reference
1.XGBoost: A Scalable Tree Boosting System
2.理解Compressed Sparse Column Format (CSC)
更多推荐


所有评论(0)