我正在努力理解切片稀疏矩阵的行为
我有这个csr矩阵说M
(0, 4136) 1
(0, 5553) 1
(0, 9089) 1
(0, 24104) 3
(0, 28061) 2
现在我提取索引(列),我想切片它。从那个矩阵我想要一个矩阵
(0, 4136) 1
(0, 5553) 1
(0, 9089) 1
(0, 24104) 3
和
(0, 28061) 2
现在,如果我这样做
M[0, training_set_index]
我得到了training_set_index=[4136,5553,9089, 24104]
(0, 3) 3
(0, 2) 1
(0, 1) 1
(0, 0) 1
我只想拥有原始矩阵(保留索引)的副本,只有training_set_index列表中指定的索引。可能吗?怎么了?
谢谢
当我听到稀疏矩阵时 - 我想到的第一件事是很多零...
其中一种方法是将稀疏矩阵转换为numpy数组 - >做一些奇特的切片 - >转回稀疏矩阵:
# create sparse matrix
training_set_index = [5553,24104] # for example I need this index
row = np.array([0, 0, 0, 0, 0])
col = np.array([4136, 5553, 9089, 24104, 28061])
data = np.array([1, 1, 1, 3, 2])
dim_0 = (1,28062)
S = csr_matrix((data, (row, col)), shape=dim_0)
print(S)
#(0, 4136) 1
#(0, 5553) 1
#(0, 9089) 1
#(0, 24104) 3
#(0, 28061) 2
# convert to numpy array
M = S.toarray()
# create np.zeros arrays and fill them with based on training_set_index
x = np.zeros((28061, ),dtype=int)
y = np.zeros((28061, ),dtype=int)
np.add.at(x, training_set_index, M[0,training_set_index])
np.add.at(y, training_set_index, M[0,28061])
# new sparse matrix
S_training = csr_matrix(x)
print(S_training)
#(0, 5553) 1
#(0, 24104) 3
有一个很好的切片!