Scipy 稀疏数组为另一个 numpy 数组的幂

问题描述 投票:0回答:1

我有一个稀疏数组,需要求另一个数组的幂:

import numpy as np
import scipy as sp

x1 = np.array([[5, 6, 7, 8, 9, 1]])
x2 = sp.sparse.csr_matrix(np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]))

但是,当我使用下面的函数时,我收到错误消息“稀疏矩阵不是方阵”。如何使用稀疏矩阵来做到这一点?

np.power(x2, x1)
python numpy scipy sparse-matrix
1个回答
0
投票

您的第二个数组没有隐式 0 值,因此不需要稀疏

In [57]: x1 = np.array([[5, 6, 7, 8, 9, 1]])
    ...: x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])

In [58]: np.power(x2,x1)
Out[58]: 
array([[   1,   64, 2187, 6561,  512,    1],
       [   1,   64, 2187, 6561,  512,    1]])

power
x2
的每个元素提升到
x1
中相应的幂。通过广播,结果是 (2,6)(即 (2,6) 与 (6,) 一起广播)

在稀疏矩阵上使用 numpy 函数时要小心。它并不总是有效。

如果我制作一个稀疏矩阵

In [61]: x3 = sparse.csr_matrix(x2)

In [62]: x3
Out[62]: 
<2x6 sparse matrix of type '<class 'numpy.intc'>'
    with 12 stored elements in Compressed Sparse Row format>

In [63]: np.power(x3,x1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[63], line 1
----> 1 np.power(x3,x1)

File ~\miniconda3\lib\site-packages\scipy\sparse\_base.py:721, in spmatrix.__pow__(self, other)
    719 M, N = self.shape[0], self.shape[1]
    720 if M != N:
--> 721     raise TypeError('matrix is not square')
    723 if isintlike(other):
    724     other = int(other)

TypeError: matrix is not square

在这里我们看到

np.power
已将任务委托给稀疏矩阵的
__pow__
方法,就像我们写的
x3**x1
一样。

如果我制作一个小方阵,我发现

**
与矩阵乘法相同。这不是重复的元素乘法。

In [74]: M=sparse.csr_matrix([[1,2],[3,4]])
In [75]: (M**3).A
Out[75]: 
array([[ 37,  54],
       [ 81, 118]], dtype=int32)
In [76]: (M*M*M).A
Out[76]: 
array([[ 37,  54],
       [ 81, 118]], dtype=int32)
© www.soinside.com 2019 - 2024. All rights reserved.