liveBook · Manning

Sparse representation

As explained in Graph Neural Networks in Action

SparseTensor is the torch_sparse sparse multidimensional tensor structure that stores values and indices rather than a full dense array.

Sparse representation stores only nonzero adjacency entries, their indices, and associated values instead of a complete N × N matrix. It is most useful for graphs with relatively few connections, where dense storage wastes memory; some operations may run more slowly than with dense data. section 7.5

A sparse graph representation separates storage choices from graph structure:

  • Store adjacency information in a sparse format such as COO, retaining nonzero indices and values. section 7.5
  • Store node features in a sparse two-dimensional tensor or in a mapping from node indices to feature vectors. section 7.5
  • Convert dense graph data with PyG’s ToSparseTensor transform or construct a torch_sparse.SparseTensor manually. section 7.5

Converting an adjacency matrix

from torch_sparse import SparseTensor dense_adj = ... sparse_adj = SparseTensor.from_dense(dense_adj) section 7.5

torch_geometric.transforms import ToSparseTensor

dataset = YourDataset(transform=ToSparseTensor())

Use ToSparseTensor when defining a PyG dataset to convert its graph representation into sparse form. section 7.5

from torch_sparse import SparseTensor

dense_adj = ...    #1
sparse_adj = SparseTensor.from_dense(dense_adj)

Use SparseTensor.from_dense for an explicit conversion from a dense adjacency matrix. section 7.5

How Graph Neural Networks in Action covers it

How deep it goes
Defines sparse storage, compares it with dense storage, and demonstrates two PyG conversion routes without detailing sparse operation internals.
Examples
Uses PyG’s ToSparseTensor dataset transform and SparseTensor.from_dense with a dense adjacency matrix.
What it assumes
Assumes familiarity with graph adjacency matrices and node features while introducing the distinction between sparse and dense storage.
What you can do after
Apply it via PyTorch Geometric or torch_sparse to convert dense graph data into a memory-efficient sparse representation.
How it connects
Connects adjacency matrices, node features, COO format, PyTorch Geometric, dense representation, and torch_sparse.SparseTensor.

Also explained in

Compare how 4 books explain sparse representation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Graph Neural Networks in Action. The section links point to the parts of the book it draws on.