Return the number of nodes in the graph. Parameters ---------- ntype : str, optional The node type name. If given, it returns the number of nodes of the type. If not given (default), it returns the total number of nodes of all types. Returns
(self, ntype=None)
| 2491 | return self.num_nodes(ntype) |
| 2492 | |
| 2493 | def num_nodes(self, ntype=None): |
| 2494 | """Return the number of nodes in the graph. |
| 2495 | |
| 2496 | Parameters |
| 2497 | ---------- |
| 2498 | ntype : str, optional |
| 2499 | The node type name. If given, it returns the number of nodes of the |
| 2500 | type. If not given (default), it returns the total number of nodes of all types. |
| 2501 | |
| 2502 | Returns |
| 2503 | ------- |
| 2504 | int |
| 2505 | The number of nodes. |
| 2506 | |
| 2507 | Examples |
| 2508 | -------- |
| 2509 | |
| 2510 | The following example uses PyTorch backend. |
| 2511 | |
| 2512 | >>> import dgl |
| 2513 | >>> import torch |
| 2514 | |
| 2515 | Create a graph with two node types -- 'user' and 'game'. |
| 2516 | |
| 2517 | >>> g = dgl.heterograph({ |
| 2518 | ... ('user', 'follows', 'user'): (torch.tensor([0, 1]), torch.tensor([1, 2])), |
| 2519 | ... ('user', 'plays', 'game'): (torch.tensor([3, 4]), torch.tensor([5, 6])) |
| 2520 | ... }) |
| 2521 | |
| 2522 | Query for the number of nodes. |
| 2523 | |
| 2524 | >>> g.num_nodes('user') |
| 2525 | 5 |
| 2526 | >>> g.num_nodes('game') |
| 2527 | 7 |
| 2528 | >>> g.num_nodes() |
| 2529 | 12 |
| 2530 | """ |
| 2531 | if ntype is None: |
| 2532 | return sum( |
| 2533 | [ |
| 2534 | self._graph.num_nodes(ntid) |
| 2535 | for ntid in range(len(self.ntypes)) |
| 2536 | ] |
| 2537 | ) |
| 2538 | else: |
| 2539 | return self._graph.num_nodes(self.get_ntype_id(ntype)) |
| 2540 | |
| 2541 | def number_of_src_nodes(self, ntype=None): |
| 2542 | """Alias of :meth:`num_src_nodes`""" |