{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### Machine Learning with Graphs 2026/27" ] }, { "cell_type": "markdown", "metadata": { "id": "IrKcrbl3ELXc" }, "source": [ "# Reasoning over knowledge graphs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this notebook, you should use the *TransE* model to generate \"shallow\" embeddings for entities and relations in a knowledge graph, and then use these to perform reasoning over the knowledge graph." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "os.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"TRUE\"\n", "# conflicting OpenMP runtimes by PyTorch & cnsplots" ] }, { "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 graph neural networks, falling back to a *CPU* if no supported *GPU* is available. Make sure to move both the data and the graph neural network models to the selected device before training." ] }, { "cell_type": "code", "execution_count": 2, "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": {}, "source": [ "Consider a scholarly knowledge graph derived from the *Microsoft Academic Graph*. This knowledge graph contains $5$,$047$ machine learning papers across $1$,$923$ research domains or topics, authored by $8$,$680$ scholars from $692$ universities, and published in $20$ computer science conferences (see [schema](https://github.com/tranhungnghiep/KG20C)). In total, the knowledge graph includes $16$,$362$ distinct entities linked by $55$,$607$ relation triples. Since your goal is to perform reasoning over the entire knowledge graph, you should train the entity and relation embeddings on all available triples, including those from the training, validation, and test sets." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Data(edge_index=[2, 55607], edge_type=[55607], num_nodes=16362)\n" ] } ], "source": [ "root = \"../data/KG20C\"\n", "splits = 'train,valid,test'\n", "\n", "entities = {}\n", "with open(root + \"/all_entity_info.txt\", 'r') as file:\n", " file.readline()\n", " for line in file:\n", " id, name, type = line.strip().split(\"\\t\")\n", " index = len(entities)\n", " entities[id] = (index, name, type)\n", "\n", "relations = {}\n", "with open(root + \"/all_relation_info.txt\", 'r') as file:\n", " file.readline()\n", " for line in file:\n", " name = line.strip()\n", " index = len(relations)\n", " relations[name] = index\n", "\n", "edge_index, edge_type = [], []\n", "for split in splits.split(','):\n", " with open(root + \"/\" + split + \".txt\", 'r') as file:\n", " for line in file:\n", " head, relation, tail = line.strip().split(\"\\t\")\n", " edge_index.append([entities[head][0], entities[tail][0]])\n", " edge_type.append(relations[relation])\n", "\n", "data = torch_geometric.data.Data(edge_index=torch.tensor(edge_index).T, edge_type=torch.tensor(edge_type), num_nodes=len(entities))\n", "data.to(device)\n", "\n", "print(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function `train` performs one epoch of training for the specified knowledge graph model." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "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": {}, "source": [ "Train the *TransE* model for a large enough number of epochs." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model = torch_geometric.nn.TransE(\n", " num_nodes=data.num_nodes,\n", " num_relations=data.num_edge_types,\n", " hidden_channels=128,\n", ").to(device)\n", "\n", "# Train on every available triple, as requested in the notebook introduction.\n", "optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n", "epochs = 1000\n", "\n", "for epoch in range(1, epochs + 1):\n", " loss = train(data, model, optimizer)\n", " if epoch % 100 == 0:\n", " print(f\"Epoch: {epoch:04d}/{epochs}, Loss: {loss:.4f}\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let’s visualize the learned entity embeddings to see how well different types are separated." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import cnsplots as cns\n", "import matplotlib.pyplot as plt\n", "from sklearn.decomposition import PCA\n", "\n", "model.cpu()\n", "embs2D = PCA(n_components=2).fit_transform(model.node_emb.weight.detach().numpy())\n", "df = pd.DataFrame([{\"x\": embs2D[index, 0], \"y\": embs2D[index, 1], \"type\": type} for index, _, type in entities.values()])\n", "\n", "cns.figure(256, 256, \"Cell\")\n", "palette = dict(zip(df.type.unique(), plt.rcParams['axes.prop_cycle'].by_key()['color']))\n", "ax = cns.scatterplot(data=df[df.type != \"conference\"], x=\"x\", y=\"y\", hue=\"type\", s=2, palette=palette)\n", "ax = cns.scatterplot(data=df[df.type == \"conference\"], x=\"x\", y=\"y\", hue=\"type\", s=48, marker=\"*\", palette=palette, ax=ax)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following functions can be used to perform multi-hop queries over a knowledge graph using entity and relation embeddings learned by the *TransE* model, which naturally supports composition and inverse relations." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_entity_emb(entity_name):\n", " # Entity names in KG20C are stored in lowercase; case-fold for robust lookup.\n", " query = entity_name.casefold()\n", " for index, name, _ in entities.values():\n", " if name.casefold() == query:\n", " return model.node_emb.weight[index]\n", " raise KeyError(f\"Entity not found in KG20C: {entity_name!r}\")\n", "\n", "def get_relation_emb(relation_name):\n", " return model.rel_emb.weight[relations[relation_name]]\n", "\n", "def print_entity_scores(source_name, reasoning, target_type, n=25):\n", " target_emb = get_entity_emb(source_name).detach().clone()\n", " for relation_name, inverse_relation in reasoning:\n", " target_emb += (-1 if inverse_relation else 1) * get_relation_emb(relation_name)\n", "\n", " entity_scores = []\n", " source_key = source_name.casefold()\n", " for index, name, entity_type in entities.values():\n", " # Do not return the source entity itself for same-type queries.\n", " if name.casefold() == source_key:\n", " continue\n", " if target_type is None or entity_type == target_type:\n", " score = (target_emb - model.node_emb.weight[index]).norm(dim=-1).item()\n", " entity_scores.append((score, name, entity_type))\n", " entity_scores.sort()\n", "\n", " print(\" Score | Entity (type)\")\n", " for score, name, entity_type in entity_scores[:n]:\n", " print(f'{score:.7f} | \"{name:s}\" ({entity_type:s})')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Which institutions do researchers from the University of Ljubljana collaborate with?*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Affiliation -> its researchers -> their papers -> co-authors -> co-authors' affiliations.\n", "# author_in_affiliation is traversed backwards to go from affiliation to author;\n", "# author_write_paper is traversed forwards and then backwards to find co-authors.\n", "# Note: this closed path uses each relation once in each direction, so its ideal\n", "# TransE translation sums to zero; interpret this ranking as an embedding-space\n", "# similarity signal, not as a strict proof of collaboration.\n", "reasoning = [\n", " (\"author_in_affiliation\", True),\n", " (\"author_write_paper\", False),\n", " (\"author_write_paper\", True),\n", " (\"author_in_affiliation\", False),\n", "]\n", "print_entity_scores(\n", " source_name=\"university of ljubljana\",\n", " reasoning=reasoning,\n", " target_type=\"affiliation\",\n", " n=25,\n", ")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Which venues do papers by researchers from the University of Ljubljana appear in?*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Affiliation -> its researchers -> their papers -> publication venues.\n", "reasoning = [\n", " (\"author_in_affiliation\", True),\n", " (\"author_write_paper\", False),\n", " (\"paper_in_venue\", False),\n", "]\n", "print_entity_scores(\n", " source_name=\"university of ljubljana\",\n", " reasoning=reasoning,\n", " target_type=\"conference\",\n", " n=25,\n", ")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Which topics do papers citing researchers from the University of Ljubljana focus on?*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Affiliation -> its researchers -> their papers -> papers citing those papers -> topics.\n", "# In KG20C, paper_cite_paper points from the citing paper to the cited paper,\n", "# so it must be traversed backwards to find papers that cite the researchers' papers.\n", "reasoning = [\n", " (\"author_in_affiliation\", True),\n", " (\"author_write_paper\", False),\n", " (\"paper_cite_paper\", True),\n", " (\"paper_in_domain\", False),\n", "]\n", "print_entity_scores(\n", " source_name=\"university of ljubljana\",\n", " reasoning=reasoning,\n", " target_type=\"domain\",\n", " n=25,\n", ")\n" ] } ], "metadata": { "colab": { "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 }