简体   繁体   中英

How to get Minimum Spanning Tree Matrix in python

Initially, i have 2d array. By using this array i have created a graph with weight on its edges. Now i am trying to use this Graph to make Minimum Spanning Tree matrix but i cant make it as desire. I am using the following code to make graph.

 G = nx.from_numpy_matrix(ED_Matrix, create_using=nx.DiGraph)
 layout = nx.spring_layout(G)
 sizes = len(ED_Matrix)
 nx.draw(G, layout, with_labels=True, node_size=sizes)
 labels = nx.get_edge_attributes(G, "weight")
 output = nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels)
 plt.show()

And its gives the output like this在此处输入图片说明

Now i am using MST code, to get the its MST matrix but its gives error like this.

 from scipy.sparse import csr_matrix
 from scipy.sparse.csgraph import minimum_spanning_tree
 Tcsr = minimum_spanning_tree(G)
 Tcsr.toarray().astype(int)

在此处输入图片说明

Taking into account example from docs of scipy , it should be constructed from adjacency matrix of G, not from G.

You might want to replace G with nx.adjacency_matrix(G) or csr_matrix(nx.adjacency_matrix(G)) or ED_Matrix itself in calculation (assignment) of Tcsr :

Tcsr = minimum_spanning_tree(nx.adjacency_matrix(G)) #or
Tcsr = minimum_spanning_tree(csr_matrix(nx.adjacency_matrix(G))) #or
Tcsr = minimum_spanning_tree(ED_Matrix)

Tcsr is a sparse matrix which is later converted to numpy array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM