python中矩阵乘法中稀疏矩阵与稠密矩阵的区别

2024-10-01 00:18:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python计算二维函数的一阶导数。为此,我写了以下脚本:

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import scipy.sparse as scspar

r_num = 10000
r_vec = np.linspace(-10, 10, r_num)
X_mat, Y_mat = np.meshgrid(r_vec, r_vec)

x_square = lambda X, Y: np.exp(-np.power(X, 2)/2-np.power(Y, 2)/2)
dh = abs(r_vec[1]-r_vec[0])

A = (np.eye(r_num)*(-30)+np.eye(r_num, k=-1)*(16)+np.eye(r_num, k=1)*(16)-np.eye(r_num, k=2)-np.eye(r_num, k=-2))/(12*dh*dh)
C = (np.eye(r_num)*(-30)+np.eye(r_num, k=-1)*(16)+np.eye(r_num, k=1)*(16)-np.eye(r_num, k=-2)-np.eye(r_num, k=2))/(12*dh*dh)
B = scspar.csc_matrix((np.eye(r_num)*-30+np.eye(r_num, k=-1)*16+np.eye(r_num, k=1)*16-np.eye(r_num, k=-2)-np.eye(r_num, k=2))/(12*dh*dh))
T = x_square(X_mat, Y_mat)

plt.imshow(A-B)
plt.show()

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X_mat, Y_mat, T*B+(T.transpose()*B).transpose())
plt.show()

现在矩阵A和{}是相等的,除了一个定义为稀疏,另一个定义为稠密。但是当更换线路时

^{pr2}$

T*A+(T.transpose()*A).transpose()

结果发生了显著变化。为什么?在


Tags: fromimportasshownppltnumdh
1条回答
网友
1楼 · 发布于 2024-10-01 00:18:03

如果它们是相同的,它们应该有相同的结果。因此,你可以断定你在某个地方犯了错误。在

scipy docs

Despite their similarity to NumPy arrays, it is strongly discouraged to use NumPy functions directly on these matrices because NumPy may not properly convert them for computations, leading to unexpected (and incorrect) results. If you do want to apply a NumPy function to these matrices, first check if SciPy has its own implementation for the given sparse matrix class, or convert the sparse matrix to a NumPyarray (e.g. using the toarray() method of the class) first before applying the method.

实际上,文档告诉我们不要在这些稀疏矩阵上使用numpy函数,而是使用specialized functions from scipy对稀疏矩阵进行操作。在

相关问题 更多 >