python – 将稀疏数组中的元素与矩阵中的行相乘

python – 将稀疏数组中的元素与矩阵中的行相乘,第1张

概述如果你有一个稀疏矩阵X: >> X = csr_matrix([[0,2,0,2],[0,2,0,1]])>> print type(X) >> print X.todense() <class 'scipy.sparse.csr.csr_matrix'>[[0 2 0 2] [0 2 0 1]] 矩阵Y: >> print type(Y)>> print text_sco 如果你有一个稀疏矩阵X:
>> X = csr_matrix([[0,2,2],[0,1]])>> print type(X)    >> print X.todense()    <class 'scipy.sparse.csr.csr_matrix'>[[0 2 0 2] [0 2 0 1]]

矩阵Y:

>> print type(Y)>> print text_scores<class 'numpy.matrixlib.defmatrix.matrix'>[[8] [5]]

…如何将X的每个元素乘以Y的行.例如:

[[0*8 2*8 0*8 2*8] [0*5 2*5 0*5 1*5]]

要么:

[[0 16 0 16] [0 10 0 5]]

我已经厌倦了这个,但显然它不起作用,因为尺寸不匹配:
Z = X.data * Y.

解决方法 不幸的是,如果另一个密集的话,CSR矩阵的.multiply方法似乎会使矩阵变得密集.所以这将是一种避免这种情况的方法:
# Assuming that Y is 1D,might need to do Y = Y.A.ravel() or such...# just to make the point that this works only with CSR:if not isinstance(X,scipy.sparse.csr_matrix):    raise ValueError('Matrix must be CSR.')Z = X.copy()# simply repeat each value in Y by the number of nnz elements in each row: Z.data *= Y.repeat(np.diff(Z.indptr))

这确实会产生一些临时性,但至少它是完全矢量化的,并且它不会使稀疏矩阵变得密集.

对于COO矩阵,等价物是:

Z.data *= Y[Z.row] # you can use np.take which is faster then indexing.

对于CSC矩阵,等价物将是:

Z.data *= Y[Z.indices]
总结

以上是内存溢出为你收集整理的python – 将稀疏数组中的元素与矩阵中的行相乘全部内容,希望文章能够帮你解决python – 将稀疏数组中的元素与矩阵中的行相乘所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1206524.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存