稀疏矩阵coo_matrix的乘法

稀疏矩阵的乘法在做基于n-gram的分类的时候还是相当有用的,但是由于网上资料太少,所以折腾了几天才算折腾出来。

首先scipy包里常见的稀疏矩阵有三种形式, coo_matrix, csr_matrix, csc_matrix.

coo_matrix: A sparse matrix in COOrdinate format.

csc_matrix: Compressed Sparse Column matrix

csr_matrix: Compressed Sparse Row matrix

基本上csr和csc的乘法都和coo差不多,理解coo的乘法即可

网上讲解coo矩阵乘法的有这样一篇文章:
http://www.mathcs.emory.edu/~cheung/Courses/561/Syllabus/3-C/sparse.html

但是他的解法应该是错的,正确的应该是

Val[N]: contains the value of the non-zero elements
Row[N]: contains the row-index of the non-zero elements
Col[N]: contains the column -index of the non-zero elements

Result保存结果

for (k = 0; k < N; k = k + 1)
result[i] = 0;
for (k = 0; k < nnz; k = k + 1)
result[Col[k]] = result[Col[k]] + Val[k]*d[Row[k]];

上代码证明:

import numpy as np
from scipy import sparse

row = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 5, 5, 6, 6, 6, 7, 7])
col = np.array([0, 1, 3, 1, 2, 4, 0, 2, 3, 1, 4, 5, 4, 4, 5, 6, 4, 6, 7, 6, 7])
data = np.array([11, 12, 14, 22, 23, 25, 31, 33, 34, 42, 45, 46, 55, 65, 66, 67, 75, 77, 78, 87, 88])
mtx = sparse.csc_matrix((data, (row,col)), shape=(8, 8))
val = np.array([1, 0, 0, 0, 0, 0, 0, 0])

results = np.zeros(8, dtype=np.int8)

k = 0

while k<len(data):
  results[col[k]] = results[col[k]] + data[k]*val[row[k]]
  k = k + 1

a = val * mtx

print a
print reults

上一篇:Fiddler抓包6-get请求(url详解)【转载】


下一篇:如何使用fiddler抓取https请求(PC和移动端)