A PyTorch Geometric Data object packages a graph for processing by graph neural networks. In a homogeneous graph workflow, it holds connectivity such as edge_index alongside node features in data.x and labels in data.y. Converting a NetworkX graph with from_networkx creates the graph structure, after which tensors and metadata can be attached for training. section 4.3.2
Build and use a Data object through this practical pipeline:
- Convert a graph into PyG form with from_networkx, then assign feature and label tensors such as data.x and data.y. section 4.3.2
- Pass data.x and data.edge_index into a GCN; use masks to calculate loss on training nodes while forwarding the entire graph. section 4.3.2
- Choose dense or sparse storage according to graph connectivity: dense tensors suit highly connected graphs, while sparse formats reduce memory for sparse graphs. section 7.5
Preparing a GCN dataset
Create a NetworkX graph, convert it with data = from_networkx(g), assign data.x = torch.tensor(features).float() and data.y = torch.tensor(labels), then record data.num_node_features. A GCN can consume data.x and data.edge_index, while a training mask selects nodes for the loss. section 4.3.2
torch_geometric.transforms import ToSparseTensor dataset = YourDataset(transform=ToSparseTensor())
Convert a dense adjacency matrix or edge index into sparse storage with the built-in ToSparseTensor transform. section 7.5
