【发布时间】:2016-12-20 16:25:20
【问题描述】:
我尝试使用以下代码生成网络矩阵。有了这个矩阵,我想找到不在对角线上的 20 个权重最高的边(i.e. i!=j 在矩阵中)。我还想获取由这些边组成的节点的名称(成对)。
import heapq
def mapper_network(self, _, info):
G = nx.Graph() #create a graph
for i in range(len(info)):
edge_from = info[0] # edge from
edge_to = info[1] # edge to
weight = info[2] # edge weight
G.add_edge(edge_from, edge_to, weight=weight) #insert the edge to the graph
A = nx.adjacency_matrix(G) # create an adjacency matrix
A_square = A * A # find the product of the matrix
print heapq.nlargest(20, A_square) # to print out the 20 highest weighted edges
但是,使用此代码,我未能生成 20 个权重最大的边。我得到raise ValueError("The truth value of an array with more than one "
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
相反,用这个
print heapq.nlargest(20, range(len(A_square)), A_square.take)
它给了我:
raise TypeError("sparse matrix length is ambiguous; use getnnz()"
TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0]
有
def mapper_network(self, _, info):
G = nx.Graph()
for i in range(len(info)):
edge_from = info[0]
edge_to = info[1]
weight = info[2]
G.add_edge(edge_from, edge_to, weight=weight)
A = nx.adjacency_matrix(G)
A_square = A * A #can print (A_square.todense())
weight = nx.get_edge_attributes(A_square, weight)
edges = A_square.edges(data = True)
s = sorted(G.edges(data=True), key=lambda (source, target, data): data['weight'])
print s
我收到了
File "/tmp/MRQ7_trevor.vagrant.20160814.040827.770006/job_local_dir/1/mapper/0/mrjob.tar.gz/mrjob/job.py", line 433, in run
mr_job.execute()
File "/tmp/MRQ7_trevor.vagrant.20160814.040827.770006/job_local_dir/1/mapper/0/mrjob.tar.gz/mrjob/job.py", line 442, in execute
self.run_mapper(self.options.step_num)
File "/tmp/MRQ7_trevor.vagrant.20160814.040827.770006/job_local_dir/1/mapper/0/mrjob.tar.gz/mrjob/job.py", line 507, in run_mapper
for out_key, out_value in mapper(key, value) or ():
File "MRQ7_trevor.py", line 90, in mapper_network
weight = nx.get_edge_attributes(A_square, weight)
File "/home/vagrant/anaconda/lib/python2.7/site-packages/networkx/classes/function.py", line 428, in get_edge_attributes
if G.is_multigraph():
File "/home/vagrant/anaconda/lib/python2.7/site-packages/scipy/sparse/base.py", line 499, in __getattr__
raise AttributeError(attr + " not found")
AttributeError: is_multigraph not found
有人可以帮我解决这个问题吗?非常感谢!
【问题讨论】:
标签: python matrix scipy heap networkx