当我发现以下奇怪现象时,我在networkx中使用以下代码块。在第一种情况下,我在稀疏矩阵上使用了ufunc multiply(*),这意外地正确地给了我一个度数序列。然而,当使用普通矩阵完成同样的操作时,它会给我一个10 x 10的矩阵,并且正如预期的那样np.dot(...)给了我正确的结果。具有邻接矩阵的乘法和点乘积(numpy)
import numpy as np
import networks as nx
ba = nx.barabasi_albert_graph(n=10, m=2)
A = nx.adjacency_matrix(ba)
# <10x10 sparse matrix of type '<class 'numpy.int64'>'
# with 32 stored elements in Compressed Sparse Row format>
A * np.ones(10)
# output: array([ 5., 3., 4., 5., 4., 3., 2., 2., 2., 2.])
nx.degree(ba)
# output {0: 5, 1: 3, 2: 4, 3: 5, 4: 4, 5: 3, 6: 2, 7: 2, 8: 2, 9: 2}
B = np.ones(100).reshape(10, 10)
B * np.ones(10)
array([[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])
np.dot(B, np.ones(10))
# array([ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.])
我期待,我应该做np.dot(A, np.ones(10))
,但返回的10数组,10×10的矩阵
array([ <10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>,
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>,
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>,
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>,
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>,
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>,
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>,
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>,
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>,
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 32 stored elements in Compressed Sparse Row format>], dtype=object)
什么是这里的细微差别?
在这种情况下,是一种幸福,因为代码看起来更清洁,而表达式的两边可能会发生两种截然不同的事情。例如,在我的代码中有一个表达式是这样的:'A * np.ones(10)> np.random.uniform(10)* np.ones(10)'。 LHS和RHS是不同类型的乘法,但数学很明确! – buzaku