[英]Multiply columns of CSR sparse matrix
我有以下稀疏的 CSR 矩陣
from scipy.sparse import csr_matrix
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])
matrix = csr_matrix((data, (row, col)), shape=(3, 3))
而這個數組
weights = np.asarray([3, 6, 9])
我想做以下事情
matrix.toarray() * weights
但沒有將稀疏矩陣轉換為密集數組。
我試着做
matrix * weights
但這確實是點積,而不是我想要的列乘法。
知道如何在不將整個 CSR 矩陣轉換為密集數組的情況下實現這一點嗎?
對於這個矩陣:
>>> matrix.A
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])
標准乘法默認為點積( matrix @ weights
也是如此):
>>> matrix * weights
array([21, 27, 96])
雖然有一個逐點乘法 function 。 這使列相乘:
>>> matrix.multiply(weights).A
array([[ 3, 0, 18],
[ 0, 0, 27],
[12, 30, 54]])
您還可以使用它通過廣播來增加行數:
>>> matrix.multiply(weights[:, np.newaxis]).A
array([[ 3, 0, 6],
[ 0, 0, 18],
[36, 45, 54]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.