# 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 node v exists in the new graph if and only if a path with length k exists from node u to node v in the original graph.

The adjacency matrix of the returned graph is $$A^k$$ (where $$A$$ is the adjacency matrix of $$g$$).

Parameters
• g (DGLGraph) – The input graph.

• k (int) – The $$k$$ in k-hop graph.

• copy_ndata (bool, optional) –

If True, the node features of the new graph are copied from the original graph.

If False, the new graph will not have any node features.

(Default: True)

Returns

The returned graph.

Return type

DGLGraph

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() and dgl.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.transform.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={})