稀疏矩阵可视化
Sparse matrix visualisation
我正在从事 FEM 分析。我只是想评估一个简单的矩阵乘法并查看数值结果。如何查看稀疏矩阵的元素?
我用过的代码是:
U_h= 0.5 * np.dot(np.dot(U[np.newaxis], K), U[np.newaxis].T)
由于 U 是 1x3 矩阵,K 是 3x3 矩阵,U.T 是 3x1 矩阵,我希望 1x1 矩阵中只有一个数字。但是,结果是“[[<3x3 稀疏矩阵类型 'class 'numpy.float64' 具有压缩稀疏行格式的 3 个存储元素>]]”
In [260]: M = sparse.random(5,5,.2, format='csr')
得到的是矩阵的repr
格式:
In [261]: M
Out[261]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 5 stored elements in Compressed Sparse Row format>
In [262]: repr(M)
Out[262]: "<5x5 sparse matrix of type '<class 'numpy.float64'>'\n\twith 5 stored elements in Compressed Sparse Row format>"
打印使用的str
格式为:
In [263]: print(M)
(1, 0) 0.7152749140462651
(1, 1) 0.4298096228326874
(1, 3) 0.8148327301300698
(4, 0) 0.23366934073409018
(4, 3) 0.6117499168861333
In [264]: str(M)
Out[264]: ' (1, 0)\t0.7152749140462651\n (1, 1)\t0.4298096228326874\n (1, 3)\t0.8148327301300698\n (4, 0)\t0.23366934073409018\n (4, 3)\t0.6117499168861333'
如果矩阵不大,将其显示为密集数组很好。 M.toarray()
这样做,或者简称:
In [265]: M.A
Out[265]:
array([[0. , 0. , 0. , 0. , 0. ],
[0.71527491, 0.42980962, 0. , 0.81483273, 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0.23366934, 0. , 0. , 0.61174992, 0. ]])
- 图形检查使用 plt.spy()
- 查看应用示例
- 参见参考手册here
我正在从事 FEM 分析。我只是想评估一个简单的矩阵乘法并查看数值结果。如何查看稀疏矩阵的元素?
我用过的代码是:
U_h= 0.5 * np.dot(np.dot(U[np.newaxis], K), U[np.newaxis].T)
由于 U 是 1x3 矩阵,K 是 3x3 矩阵,U.T 是 3x1 矩阵,我希望 1x1 矩阵中只有一个数字。但是,结果是“[[<3x3 稀疏矩阵类型 'class 'numpy.float64' 具有压缩稀疏行格式的 3 个存储元素>]]”
In [260]: M = sparse.random(5,5,.2, format='csr')
得到的是矩阵的repr
格式:
In [261]: M
Out[261]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 5 stored elements in Compressed Sparse Row format>
In [262]: repr(M)
Out[262]: "<5x5 sparse matrix of type '<class 'numpy.float64'>'\n\twith 5 stored elements in Compressed Sparse Row format>"
打印使用的str
格式为:
In [263]: print(M)
(1, 0) 0.7152749140462651
(1, 1) 0.4298096228326874
(1, 3) 0.8148327301300698
(4, 0) 0.23366934073409018
(4, 3) 0.6117499168861333
In [264]: str(M)
Out[264]: ' (1, 0)\t0.7152749140462651\n (1, 1)\t0.4298096228326874\n (1, 3)\t0.8148327301300698\n (4, 0)\t0.23366934073409018\n (4, 3)\t0.6117499168861333'
如果矩阵不大,将其显示为密集数组很好。 M.toarray()
这样做,或者简称:
In [265]: M.A
Out[265]:
array([[0. , 0. , 0. , 0. , 0. ],
[0.71527491, 0.42980962, 0. , 0.81483273, 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0.23366934, 0. , 0. , 0.61174992, 0. ]])
- 图形检查使用 plt.spy()
- 查看应用示例
- 参见参考手册here