Aura Graph Analytics: GraphSAGE node classification via sessions

This Jupyter notebook is hosted here in the Neo4j Graph Data Science Client Github repository.

The notebook shows how to use the graphdatascience Python library to train a supervised GraphSAGE model on Cora and run node classification inference on an Aura Graph Analytics (AGA) Session, using the typed gds.graph_sage.supervised endpoints.

Prerequisites

This notebook requires having the Aura Graph Analytics feature enabled for your Neo4j Aura project, and a session backed by the Python runtime.

You also need to have the graphdatascience Python library installed, version 2.1 or later.

%pip install "graphdatascience>=2.1" python-dotenv matplotlib

Credentials

import os

from dotenv import load_dotenv

# This allows to load required secrets from `.env` file in local directory
load_dotenv(".env")

Aura API credentials

from graphdatascience.session import AuraAPICredentials, GdsSessions

api_credentials = AuraAPICredentials(
    client_id=os.environ["CLIENT_ID"],
    client_secret=os.environ["CLIENT_SECRET"],
    # If your account is a member of several projects, you must also specify the project ID to use
    project_id=os.environ.get("PROJECT_ID", None),
)

sessions = GdsSessions(api_credentials=api_credentials)

Creating a new session

A new session is created by calling sessions.get_or_create() with a representative name, the session memory, the cloud location, and a time-to-live (TTL), which ensures that the session is automatically deleted after being unused for the set time, to avoid incurring costs.

from datetime import timedelta

from graphdatascience.session import CloudLocation, SessionMemory

# Explicitly define the size of the session
memory = SessionMemory.m_4GB

# Specify your cloud location
cloud_location = CloudLocation("gcp", "europe-west1")

# Create a GDS session!
gds = sessions.get_or_create(
    # we give it a representative name
    session_name="graphsage-supervised",
    memory=memory,
    ttl=timedelta(minutes=30),
    cloud_location=cloud_location,
)

# Verify the connectivity. Hints towards TLS or firewall issues if this fails directly after get_or_create
gds.verify_connectivity()

Load Cora

The Cora citation dataset ships with the client and is loaded directly into the session: Paper nodes carry a numeric features vector and a subject class label, connected by CITES relationships.

gds.graph.drop("cora", fail_if_missing=False)
gds.model.delete("gds_demo_graphsage_supervised", fail_if_missing=False)

G = gds.graph.datasets.load_cora()
print("Loaded graph:", G.name())

Train GraphSAGE (Supervised)

gds.graph_sage.supervised.train submits the training job, blocks until completion (with progress reporting), and returns the trained model together with a train summary result.

model, train_result = gds.graph_sage.supervised.train(
    G,
    model_name="gds_demo_graphsage_supervised",
    feature_properties=["features"],
    target_label="Paper",
    target_property="subject",
    epochs=15,
    epochs_per_val=2,
    embedding_dimension=256,
    learning_rate=0.001,
    num_neighbors=[20, 20],
    batch_size=512,
    activation_function="relu",
    aggregator="mean",
    random_seed=42,
)

print("Trained model:", model.name())
train_result

Run Inference

gds.graph_sage.supervised.stream runs the predict job against the stored model and streams the results. Supervised GraphSAGE returns one row per node with predictedClass and predictedProbabilities.

predictions_df = gds.graph_sage.supervised.stream(
    G,
    model_name=model.name(),
    feature_properties=["features"],
    random_seed=42,
)

assert set(predictions_df.columns) == {"nodeId", "predictedClass", "predictedProbabilities"}
predictions_df

Predicted class distribution

import matplotlib.pyplot as plt

counts = predictions_df["predictedClass"].value_counts().sort_index()

fig, ax = plt.subplots(figsize=(8, 4))
ax.bar([str(c) for c in counts.index], counts.to_numpy(), color="skyblue", edgecolor="black")
ax.set_title("Predicted subject distribution (Cora papers)")
ax.set_xlabel("predicted class")
ax.set_ylabel("number of papers")
fig.tight_layout()
plt.show()

Cleanup

After the analysis is done, we delete the trained model and the graph, and then delete the session. Deleting the session releases all resources associated with it, and stops incurring costs.

gds.model.delete("gds_demo_graphsage_supervised", fail_if_missing=False)

G.drop(fail_if_missing=False)
sessions.delete(session_name="graphsage-supervised")