dgl.khop_graphο
- dgl.khop_graph(g, k, copy_ndata=True)[source]ο
Return the graph whose edges connect the
k
-hop neighbors of the original graph.More specifically, an edge from node
u
and nodev
exists in the new graph if and only if a path with lengthk
exists from nodeu
to nodev
in the original graph.The adjacency matrix of the returned graph is \(A^k\) (where \(A\) is the adjacency matrix of \(g\)).
- Parameters:
- Returns:
The returned graph.
- Return type:
Notes
If
copy_ndata
is True, the resulting graph will share the node feature tensors with the input graph. Hence, users should try to avoid in-place operations which will be visible to both graphs.This function discards the batch information. Please use
dgl.DGLGraph.set_batch_num_nodes()
anddgl.DGLGraph.set_batch_num_edges()
on the transformed graph to maintain the information.Examples
Below gives an easy example:
>>> import dgl >>> g = dgl.graph(([0, 1], [1, 2])) >>> g_2 = dgl.transforms.khop_graph(g, 2) >>> print(g_2.edges()) (tensor([0]), tensor([2]))
A more complicated example:
>>> import dgl >>> g = dgl.graph(([0,1,2,3,4,0,1,2,3,4], [0,1,2,3,4,1,2,3,4,0])) >>> dgl.khop_graph(g, 1) DGLGraph(num_nodes=5, num_edges=10, ndata_schemes={} edata_schemes={}) >>> dgl.khop_graph(g, 3) DGLGraph(num_nodes=5, num_edges=40, ndata_schemes={} edata_schemes={})