我正在使用邻接矩阵来表示一个朋友网络,可以被视为
Mary 0 1 1 1
Joe 1 0 1 1
Bob 1 1 0 1
Susan 1 1 1 0
Mary Joe Bob Susan
我想使用这个矩阵编译出所有可能的友谊三角形列表,条件是用户1和用户2是朋友,用户2和用户3也是朋友。对于我的列表,不需要要求用户1和用户3是朋友。
(joe, mary, bob)
(joe, mary, susan)
(bob, mary, susan)
(bob, joe, susan)
我有一段代码适用于小三角形,但需要对非常大的稀疏矩阵进行扩展。
from numpy import *
from scipy import *
def buildTriangles(G):
# G is a sparse adjacency matrix
start = time.time()
ctr = 0
G = G + G.T # I do this to make sure it is symmetric
triples = []
for i in arange(G.shape[0] - 1): # for each row but the last one
J,J = G[i,:].nonzero() # J: primary friends of user i
# I do J,J because I do not care about the row values
J = J[ J < i ] # only computer the lower triangle to avoid repetition
for j in J:
K, buff = G[:,j].nonzero() # K: secondary friends of user i
K = K[ K > i ] # only compute below i to avoid repetition
for k in K:
ctr = ctr + 1
triples.append( (i,j,k) )
print("total number of triples: %d" % ctr)
print("run time is %.2f" % (time.time() - start())
return triples
我能够在约21分钟内对1032570 x 1032570的csr_matrix运行代码,其中包含88910个存储元素。总共生成了2178893个三元组。
我需要能够处理类似于1968654 x 1968654的稀疏矩阵,其中包含9428596个存储元素。
我对Python非常陌生(不到一个月的经验),而且不是线性代数方面的专家,这就是为什么我的代码没有利用矩阵操作的原因。有人能提出改进建议或让我知道我的目标是否可行吗?
J,J =
)没有任何保证的意义。我发现这非常令人困惑,你的评论也是如此,所以你可能想要摆脱它。 - Fred Foorow,col = G[i,:] .nonzero()
,然后J = col
。我使用J,J=
方法是因为我担心内存使用情况,并希望消耗掉行数组,因为它不需要。 - willdel
删除变量,尽管在这种情况下,J = G[i, :].nonzero()[1]
也可以工作。 - Fred Foo