Learning with Graph data — Basics
Networkx Python Graph package
Networkx is a an open source python package, that handles graph data structure. Networkx contain few graph algorithms, and there are other packages that implement deep learning algorithms, using networkx data structure.
Create a Graph with locations and weights
There are many options to create a graph in networkx. I will show few examples. The basic “must have” is set of nodes, and a set of edges, when en edge is defined by the start-end nodes.
Create simple Graph with locations and weights
import networkx as nx
l = [(5,7),(7,1),(7,2),(1,4),(1,6)]
Gt=nx.Graph()
Gt.add_edges_from(l)
nx.draw(Gt, with_labels=True)
Create a Graph with locations and weights
import networkx as nx
l = [('1','2',3.),('2','3',2.5),('3','4',1.5),('3','5',4.),('1','6',5.),('6','7',2.),('6','8',3.),('9','8',5.)]
Gt=nx.Graph()
Gt.add_weighted_edges_from(l)
labels = nx.get_edge_attributes(Gt,'weight')
nx.draw(Gt, with_labels=True)
Add node and edge to the graph. The node will have feature vector,
feature_vector=np.array([1,7,22])
Gt.add_node(100,v=feature_vector, label='n1')
Gt.add_edge('1', 100, weight = 8)
nx.draw(Gt, with_labels=True)
Force plotting of the graph, in the correct locations defined in the nodes.
pos = nx.spring_layout(Gt)
# Draw the graph according to node positions
nx.draw(Gt, pos, with_labels=True)
Plot edge weights
# Create edge labels
labels = {e: str(Gt.get_edge_data(e[0], e[1])['weight']) for e in Gt.edges}
labels = {e: str(Gt.get_edge_data(*e)['weight']) for e in Gt.edges}
nx.draw_networkx_edge_labels(Gt, pos, edge_labels=labels);
Code is in my git: github.com/naomifridman/Graph_learning