Skip to main content
 首页 » 编程设计

python之添加 ndarray 和在 python 中转换为密集的稀疏矩阵时出现广播错误

2025年05月04日12shihaiming

我正在从 scipy 稀疏矩阵转换为密集矩阵,并使用 += 运算符将其添加到 ndarray 中,但出现广播错误。 ndarray 的形状为 (M,),而密集矩阵的形状为 (M,1)。当我尝试将 numpy.matrix 转换为 ndarray 时,形状变为 (1,M)。我也尝试在转换后使用 reshape(M,),形状变为 (M,M)。谁能解释一下我哪里搞砸了。

M = 100 
N = 1000 
K = 4 
a= np.zeros((M,K)) 
 
b = sp.csr_matrix(np.ones((N,1))) 
d = sp.csr_matrix(np.ones((M,N))) 
 
c = np.ones(()) 
for k in range(K):  
    a[:,k] += d.dot(b).todense() 

P.S:我是 python 和 stackoverflow 的新手。如果这是一个错误的问题或者这个问题之前已经被问过(我找不到),我们深表歉意

请您参考如下方法:

给 future 的 google 员工的旁注,OP 的代码导入了以下包:

> import numpy as np 
> import scipy.sparse as sp 

不管怎样,让我们​​从我们的解释开始吧。


您可以使用以下方法检查您的矩阵大小:

> np.shape(your_matrix_here) #equals to MATLAB: > size(your_matrix_here) 

当你调用 todense() 时,你得到了:

matrix([[ 1000.],  #shape: (1, 100) 
        [ 1000.], 
        [ 1000.], 
        ... 

而 a[:,1] 看起来像这样:

array([ 0.,  0., ... ,  0.,  0.]) #shape: (100,) 

因此您可能想使用 transpose() 转置矩阵。


但是转置矩阵返回包含矩阵的矩阵:

matrix([[ 1000.,  1000., ... , 1000.,  1000.]]) #shape: (1, 100) 

并且由于某些原因 d.dot(b).todense().transpose()[0] 没有返回矩阵的第一个元素:

matrix([[ 1000.,  1000., ... , 1000.,  1000.]]) #still the same! 

这可以通过以下方式解决:

> np.array(d.dot(b).todense().transpose())[0] 

因此返回:

array([ 1000.,  1000., ... 1000.,  1000.]) 

现在他们两个得到了相同的形状,允许他们进行矩阵运算:

> np.shape(np.array(d.dot(b).todense().transpose())[0]) #(100,) 
 
> np.shape(a[:,1])                                      #(100,) 

总之,您要更改此行:

a[:,k] += d.dot(b).todense() 

到:

a[:,k] += np.array(d.dot(b).todense().transpose())[0]