An edge index is a tensor-based graph representation whose two rows store source and destination node indices. It converts original identifiers into compact, consecutive IDs that graph neural network pipelines can process reliably. section 12.1.2 section 12.2.2
Build an edge index through a short preprocessing pipeline:
- Map original node identifiers to incremental IDs, then remove edges whose endpoints cannot be mapped. section 12.1.2
- Select the mapped source and destination columns, transpose them, and create a long-integer tensor with shape [2, number of edges]. section 12.1.2 section 12.2.2
- Attach the tensor to the appropriate relationship when representing heterogeneous graphs, and add reverse edges when message passing must operate in both directions. section 12.2.3
Financial transactions and movie ratings
For transactions, source IDs 230425980 and 5530458 become nodes 0 and 1, producing an edge pair from 0 to 1. For MovieLens, the resulting edge_index has shape [2, 100836], representing user-to-movie ratings. section 12.1.2 section 12.2.2
Listing 12.15 Generating the edge_index tensor from user and movie IDs
ratings_df = pd.read_csv(ratings_path) #1
unique_user_id = ratings_df['userId'].unique()
unique_user_id = pd.DataFrame(data={
'userId': unique_user_id,
'mappedID': pd.RangeIndex(len(unique_user_id)),
}) #2
unique_movie_id = pd.DataFrame(data={
'movieId': movies_df.index,
'mappedID': pd.RangeIndex(len(movies_df)),
}) #3
ratings_user_id = pd.merge(
ratings_df['userId'],
unique_user_id,
left_on='userId',
right_on='userId',
how='left'
)
ratings_user_id = torch.from_numpy(ratings_user_id['mappedID'].values) #4
ratings_movie_id = pd.merge(
ratings_df['movieId'],
unique_movie_id,
left_on='movieId',
right_on='movieId',
how='left'
)
ratings_movie_id = torch.from_numpy(ratings_movie_id['mappedID'].values) #5
edge_index_user_to_movie = torch.stack([ratings_user_id, ratings_movie_id], dim=0) #6
Inspect the complete user-and-movie ID mapping pipeline and its resulting edge_index tensor. section 12.2.2
