[英]Re-ordering of the rows and columns in a CSR matrix
我有一個稀疏 csr 格式的矩陣,例如:
from scipy.sparse import csr_matrix
import numpy as np
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])
M = csr_matrix((data, (row, col)), shape=(3, 3))
M.A =
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])
我使用以下方法使用索引 [2,0,1] 重新排序矩陣:
order = np.array([2,0,1])
M = M[order,:]
M = M[:,order]
M.A
array([[6, 4, 5],
[2, 1, 0],
[3, 0, 0]])
這種方法有效,但對於我的真實 csr_matrix 不可行,它的大小為16580746 X 1672751804
並導致內存錯誤。 我采取了另一種方法:
edge_list = zip(row,col,dat)
index = dict(zip(order, range(len(order))))
all_coeff = zip(*((index[u], index[v],d) for u,v,d in edge_list if u in index and v in index))
new_row,new_col,new_data = all_coeff
n = len(order)
graph = csr_matrix((new_data, (new_row, new_col)), shape=(n, n))
這也有效,但對於大型稀疏矩陣陷入相同的內存錯誤陷阱。 有什么建議可以有效地做到這一點嗎?
讓我們聰明地思考。
為什么不直接處理開始時提供的行和列索引,而不是對矩陣重新排序?
因此,例如,您可以通過以下方式替換行索引:
[0, 0, 1, 2, 2, 2]
到:
[2, 2, 0, 1, 1, 1]
和您的列索引,來自:
[0, 2, 2, 0, 1, 2]
到:
[2, 1, 1, 2, 0, 1]
我發現使用矩陣運算是最有效的。 這是一個將行和/或列排列為指定順序的函數。 如果您願意,可以修改它以交換兩個特定的行/列。
from scipy import sparse
def permute_sparse_matrix(M, new_row_order=None, new_col_order=None):
"""
Reorders the rows and/or columns in a scipy sparse matrix
using the specified array(s) of indexes
e.g., [1,0,2,3,...] would swap the first and second row/col.
"""
if new_row_order is None and new_col_order is None:
return M
new_M = M
if new_row_order is not None:
I = sparse.eye(M.shape[0]).tocoo()
I.row = I.row[new_row_order]
new_M = I.dot(new_M)
if new_col_order is not None:
I = sparse.eye(M.shape[1]).tocoo()
I.col = I.col[new_col_order]
new_M = new_M.dot(I)
return new_M
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.