import scipy.sparse as sp
import numpy as np
if __name__ == '__main__':
a = sp.csr_matrix([[0., 4, 0, 8],
[8, 0, 4, 0],
[0, 0, 0, 1]], dtype=np.float32)
# recommended
rows1 = np.array(a.sum(1))
# not recommended
rows2 = np.sum(a,axis=1)
# (3, 1) (3,) (3, 1) (1, 3)
print(rows1.shape, np.squeeze(rows1).shape,rows2.shape,np.squeeze(rows2).shape)
# flatten works well
r_rec1 = np.power(rows1, 2).flatten()
# flatten does not work
r_rec2 = np.power(rows2, 2).flatten()
print(r_rec1, r_rec2)
numpy 操作于 sparse 矩阵的时候可能出现的形状问题
最新推荐文章于 2023-12-12 20:08:41 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)