标签:matrix indptr scipy sparse indices array data csr
使用形式
①csr_matrix(D)
其中D是稠密矩阵或者二维向量
②csr_matrix(S)
其中S是稀疏矩阵
③csr_matrix((M, N), [dtype])
构造一个规模为(M,N)的dtype,其中dtypy是可选的
④csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
其中满足的关系是:a[row_ind[i],col_ind[i]]=data[i],此处a是结果矩阵
⑤csr_matrix((data, indices, indptr), [shape=(M, N)])
其中满足的关系是:对于第i行有:
列索引为indices[indptr[i]:indptr[i+1]]
值为data[indptr[i]:indptr[i+1]]
例子
- csr_matrix((M, N), [dtype])
>>>import numpy as np
>>>from scipy.sparse import csr_matrix
>>>csr_matrix((3, 4), dtype=np.int8).toarray()##转化为ndarray
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
产生一个3行4列的空矩阵,数据类型为int8
- csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
>>>row = np.array([0, 0, 1, 2, 2, 2])
>>>col = np.array([0, 2, 2, 0, 1, 2])
>>>data = np.array([1, 2, 3, 4, 5, 6])
>>>csr_matrix((data, (row, col)), shape=(3, 3)).toarray()##转化为ndarray
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])
也就是在结果矩阵中的[0,0]放1,在[0,2]中放2,在[1,2]中放3......[2,2]中放6
- csr_matrix((data, indices, indptr), [shape=(M, N)])
>>>indptr = np.array([0, 2, 3, 6])
>>>indices = np.array([0, 2, 2, 0, 1, 2])
>>>data = np.array([1, 2, 3, 4, 5, 6])
>>>csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()##
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])
此处应该是有点难以理解的:
对于结果矩阵第0行:(此处默认从第0行开始),
其列索引为:indices[indptr[0]:indptr[0+1]],也就是indices[0:2],也就是indices的第0个+第1个,也就是0和2
其值为 :data[indptr[0]:indptr[0+1]],也就是data[0:2],也就是data的第一个和第二个,也就是1和2,
好了这下行索引,列索引,值都确定了,对应一下也就是第0行的第0个位置是1,第0行的第2个位置是2
对于结果矩阵第1行:(此处默认从第0行开始),
其列索引为:indices[indptr[1]:indptr[1+1]],也就是indices[2:3],也就是indices的第2个,也就是2
其值为 :data[indptr[1]:indptr[1+1]],也就是data[2:3],也就是data的第2个,也就是3
好了这下行索引,列索引,值都确定了,对应一下也就是第1行的第2个位置是3
结果矩阵的第三行也是一样的道理,此处就不在说了。
标签:matrix,indptr,scipy,sparse,indices,array,data,csr 来源: https://blog.csdn.net/yellowetao/article/details/120577783
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。