{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "bD8Y4hmEpIlV" }, "source": [ "### Machine Learning with Graphs 2026/27" ] }, { "cell_type": "markdown", "metadata": { "id": "IrKcrbl3ELXc" }, "source": [ "# Knowledge graph embeddings" ] }, { "cell_type": "markdown", "metadata": { "id": "A3NX5RuZpIlW" }, "source": [ "In this notebook, you should compare different models for learning \"shallow\" embeddings of entities and relations in a knowledge graph. which can be applied to knowledge graph completion and reasoning tasks." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The code below automatically selects an available *GPU* (i.e. *NVIDIA CUDA* or *Apple Silicon MPS*) to accelerate the training of knowledge graph models, falling back to a *CPU* if no supported *GPU* is available. Make sure to move both the knowledge graph and the models to the selected device before training and evaluation." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mps\n" ] } ], "source": [ "import torch\n", "import torch_geometric\n", "\n", "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"mps\" if torch.backends.mps.is_available() else \"cpu\")\n", "\n", "print(device)" ] }, { "cell_type": "markdown", "metadata": { "id": "KEKpjanfpIlY" }, "source": [ "Consider a subset of the *Freebase* knowledge graph containing facts about real-world entities such as people, organizations, places, events, etc. This knowledge graph contains $14$,$541$ distinct entities, $237$ types of relations, and a total of $310$,$116$ fact triples. The dataset is split into training, validation and test sets containing $272$,$115$, $17$,$535$ and $20$,$466$ triples, respectively." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "EY9ILrnZpIlY", "outputId": "9763a042-9598-434d-f854-1cf936043fd5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Data(edge_index=[2, 272115], edge_type=[272115], num_nodes=14541)\n", "Data(edge_index=[2, 17535], edge_type=[17535], num_nodes=14541)\n", "Data(edge_index=[2, 20466], edge_type=[20466], num_nodes=14541)\n" ] } ], "source": [ "train_data = torch_geometric.datasets.FB15k_237(root=\"../data/FB15k\", split=\"train\")[0]\n", "train_data.to(device)\n", "\n", "val_data = torch_geometric.datasets.FB15k_237(root=\"../data/FB15k\", split=\"val\")[0]\n", "val_data.to(device)\n", "\n", "test_data = torch_geometric.datasets.FB15k_237(root=\"../data/FB15k\", split=\"test\")[0]\n", "test_data.to(device)\n", "\n", "print(train_data)\n", "print(val_data)\n", "print(test_data)" ] }, { "cell_type": "markdown", "metadata": { "id": "cfh3r8onpIlZ" }, "source": [ "The function `train` performs one epoch of training for the specified knowledge graph model." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "id": "NsGwsfVGpIlZ" }, "outputs": [], "source": [ "def train(data, model, optimizer):\n", " model.train()\n", " optimizer.zero_grad()\n", "\n", " loss = model.loss(head_index=data.edge_index[0], rel_type=data.edge_type, tail_index=data.edge_index[1])\n", "\n", " loss.backward()\n", " optimizer.step()\n", "\n", " return loss.item()" ] }, { "cell_type": "markdown", "metadata": { "id": "4kTayihVpIlZ" }, "source": [ "The function `test` evaluates a trained knowledge graph model on a specified set of triples. It returns three performance metrics:\n", "+ `rank` is the average rank of the correct tail entity among all candidate entities (lower is better),\n", "+ `mrr` is the average reciprocal rank of the correct tail entity among all candidate entities (higher is better),\n", "+ `hits` is the proportion of predictions for which the correct tail entity is ranked among the top ten (higher is better).\n", "\n", "The evaluation considers tail prediction only and does not filter other known true triples from the candidate rankings." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "id": "7cTja6frpIla" }, "outputs": [], "source": [ "def test(data, model):\n", " model.eval()\n", "\n", " with torch.no_grad():\n", " rank, mrr, hits = model.test(head_index=data.edge_index[0], rel_type=data.edge_type, tail_index=data.edge_index[1], batch_size=1024, log=False)\n", "\n", " return rank, mrr, hits" ] }, { "cell_type": "markdown", "metadata": { "id": "5l51VTtupIla" }, "source": [ "The function `train_eval_report` trains a knowledge graph model for a given number of epochs. It evaluates the model on the validation set every five epochs, selects the model with the best validation mean reciprocal rank, and finally reports its performance on the test set." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "import copy\n", "import time\n", "\n", "def train_eval_report(train_data, val_data, test_data, model, epochs=250, lr=0.005):\n", " optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n", "\n", " tic = time.time()\n", " best_e, best_mrr, best_state = 0, 0, None\n", " for e in range(1, epochs+1):\n", " loss = train(train_data, model, optimizer)\n", "\n", " if e % 5 == 0:\n", " _, mrr, _ = test(val_data, model)\n", " if mrr > best_mrr:\n", " best_e = e\n", " best_mrr = mrr\n", " best_state = copy.deepcopy(model.state_dict())\n", "\n", " model.load_state_dict(best_state)\n", " rank, mrr, hits = test(test_data, model)\n", "\n", " print(f\" Best | {best_e:d} / {epochs:d}\")\n", " print(f\" Time | {(time.time()-tic)/60:.1f} min\\n\")\n", " print(f\" Rank (↓) | {rank:.1f} / {test_data.num_nodes}\")\n", " print(f\" MRR (↑) | {mrr:.3f}\")\n", " print(f\" Hits@10 (↑) | {100*hits:.1f}%\")" ] }, { "cell_type": "markdown", "metadata": { "id": "oBuCsKzMpIlb" }, "source": [ "## The *TransE* model" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 528 }, "id": "QEMzMxW8pIlb", "outputId": "fd9a42a9-7f23-4c20-dd8f-f373f52d32f9" }, "outputs": [], "source": [ "# TransE learns relation-specific translations between entity embeddings.\n", "model = torch_geometric.nn.TransE(\n", " num_nodes=train_data.num_nodes,\n", " num_relations=train_data.num_edge_types,\n", " hidden_channels=50,\n", ").to(device)\n", "\n", "train_eval_report(train_data, val_data, test_data, model, epochs=250, lr=0.005)\n" ] }, { "cell_type": "markdown", "metadata": { "id": "BKLGiqMupIlb" }, "source": [ "## The *DistMult* model" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 528 }, "id": "9nvJugZfpIlc", "outputId": "207797ed-71c8-48cd-c91a-574d14307156" }, "outputs": [], "source": [ "# DistMult uses a diagonal bilinear interaction for each relation.\n", "model = torch_geometric.nn.DistMult(\n", " num_nodes=train_data.num_nodes,\n", " num_relations=train_data.num_edge_types,\n", " hidden_channels=50,\n", ").to(device)\n", "\n", "train_eval_report(train_data, val_data, test_data, model, epochs=250, lr=0.001)\n" ] }, { "cell_type": "markdown", "metadata": { "id": "ocq3iBMfpIlc" }, "source": [ "## The *ComplEx* model" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 528 }, "id": "we2oEqKgpIld", "outputId": "98f200bd-f25e-4393-d319-7bc8372f7906" }, "outputs": [], "source": [ "# ComplEx represents entity and relation embeddings in complex space.\n", "model = torch_geometric.nn.ComplEx(\n", " num_nodes=train_data.num_nodes,\n", " num_relations=train_data.num_edge_types,\n", " hidden_channels=50,\n", ").to(device)\n", "\n", "train_eval_report(train_data, val_data, test_data, model, epochs=250, lr=0.001)\n" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "L4", "machine_shape": "hm", "provenance": [] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.3" } }, "nbformat": 4, "nbformat_minor": 4 }