scipy库中的csr_matrix和csc_matrix
from scipy.sparse import csr_matrix
from scipy.sparse import csc_matrix
import numpy as np
>>> 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()
# 记为res_csr
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])
>>> 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])
# 若要生成与res_csr一致的csc_matrix矩阵,则data要为np.array([1, 4, 5, 2, 3, 6])
>>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
# 记为res_csc
array([[1, 0, 4],
[0, 0, 5],
[2, 3, 6]])
可见,同样的数据生成的res_csr与res_csc矩阵的联系在于:res_csr.T 等于 res_csc
自己理解
以csr_matrix为例子(以行为主)
· indptr = np.array([0, 2, 3, 6])为指示通过行累加的元素个数。
第一位必为0。
第二位2意味着生成的csr_matrix矩阵的第一行(累加到第一行为止,所以是第一行)有2个元素。
第三位3意味着csr_matrix矩阵的第一行和第二行(累加到第二行为止所以是前二行)共有3个元素,可推出第二行有3-2=1个元素。
第四位6意味着csr_matrix矩阵的第一行和第二行和第三行(累加到第三行为止所以是前三行)共有6个元素,可推出第三行有6-3=3个元素。
· indices = np.array([0, 2, 2, 0, 1, 2])为指示哪一列存在元素的列索引。【因为已知csr_matrix是以行为主的,相当于已知行信息了,所以需要列的指引】
indices 的第一位0表示csr_matrix矩阵的第一行的0列有元素,第二位2第一行的2列有元素。【因为已经知道第一行有两个元素了,所以第一行是[x, 0, x],x表示有元素】
第三位2表示第二行的第2列有元素。【因为已经知道第二行有一个元素了,所以第二行是[0, 0, x],x表示有元素】
第四第五第六位0和1和2表示第三行的0和1和2列都有元素。【因为已经知道第三行有一个元素了,所以第三行是[x, x, x],x表示有元素】
总的来说csr_matrix矩阵应为这样:
[x, 0, x]
[0, 0, x]
[x, x, x]
· 知道data = np.array([1, 2, 3, 4, 5, 6])那么以行为顺序,以此添加即可得到csr_matrix矩阵:
[1, 0, 2]
[0, 0, 3]
[4, 5, 6]
同理,可得csc_matrix(以列为主)。