We train a small graph neural network on smollerGraph's mammals and birds. sg export writes the graph for programs outside the database, and a script trains a GraphSAGE in PyTorch, whose layers each give a node a new vector from its own and the average of its neighbours'. Four layers reach a species' relatives through its genus and its family, and with the label trick, the network learns which species are threatened from what's known about their relatives. It does about as well as a rule written by hand, and its predictions go back into the graph, so Cypher can ask which species listed as least concern it rates at risk. It's a vanilla version of what Neo4j's Graph Data Science library offers, written to see how it works.
Topics: Machine learning on graphs
The code
Each step on screen is a tag in the database's repository. The code at the end of the episode is ep015/end.
Transcript
Intro
0:00 Hello, and welcome to episode fifteen, in which we train a small graph neural network on our mammals and birds, and load what it learns back into the graph. Here's a look at where we'll be by the end of the episode.
0:12 By the end, a network that learns from the graph is going to rate six thousand species' risk of being threatened, from what's known about their relatives. Here, Cypher asks for the species the IUCN lists as least concern that the network rates at risk, and it names fifteen, among them the common ostrich and two civets, worth a closer look.
0:32 If you'd like to know more about the project, the series' website is the place to start. The code is open source, on GitHub, with a tag at each step of each episode, so you can pick it up at any point. And each episode has a page of its own, with its chapters and its code.
Last time
0:49 Last time, each node got an embedding, a vector of numbers that stands for where it is in the graph. FastRP gave each node a random vector, then mixed in its neighbours' vectors, round after round. sg embed kept them in the graph's folder, a kibibyte for each node. Then sg similar, and the page's Similar button, found the nodes whose vectors point most nearly in one direction with a node's, such as the other big cats for the lion. But the way FastRP mixes the vectors is fixed, and nothing in it learns from what we know about the nodes. Today, the mixing gets weights, which a network learns.
Today
1:26 Here's today's work, from the database out to a model and back. A model trains outside the database, so sg export is going to write the graph in a form a script can read. The script trains a GraphSAGE, one of the best known graph neural networks, with PyTorch. It learns which species are threatened, from their weights and from what's known about their relatives. And what it predicts goes back into the graph, as a property, for Cypher to ask about. So, let's start with what a graph neural network is, and what Neo4j offers.
Graph neural networks
1:59 A graph neural network is a neural network whose layers pass messages along the relationships, so a node's vector is built from its neighbours'. FastRP, from last episode, does that with a mixing that's fixed: a sum of the neighbours, scaled. GraphSAGE, from a paper of twenty seventeen, does it with weights, so the mixing is learnt from examples, and Neo4j's Graph Data Science library offers it, as it does FastRP. The library's pipelines train a model to classify nodes, from their embeddings and their properties, and write each prediction back to its node, as a property. Ours is going to be a vanilla version of that, a script that trains outside the database, and sg load to write the predictions back. It isn't going to scale the way theirs does, and it's there to show how it works.
Message passing
2:48 Here's what a single layer of a GraphSAGE does. Each node starts with a vector of its own features, such as its weight. Each of its neighbours sends it its vector, and the node takes their average. The two go side by side, in a single vector twice as long. A matrix of weights, which training learns, turns that into a new vector, and ReLU sets its negative numbers to zero. That's the node's new vector, for the next layer. Each layer reaches a hop further, so after four layers, a node has heard from nodes four hops away. For a species, four hops go up through its genus to its family, and back down through the family's other genera to its relatives, which is where most of what we know about a species' risk is.
3:32 A species' own weight says a little about its risk, and its relatives' statuses say a lot, so the statuses go in as features too, which is called the label trick. Of the species with a status, seventy percent are for training. Each epoch, half of them show their status, as a feature, and the network learns to predict the other half from them, so no species sees its own answer. The halves are drawn again each epoch, so each species gets predicted from its relatives many times over. The other thirty percent are for checking, and their statuses aren't shown at any point, so the score on them is a fair one.
Export
4:09 A model trains outside the database, in a script, which needs the graph in a form it can read. The export writes properties as JSON, as the page gets them, so in the API's header file, we include vector, for the list of properties, and Properties JSON comes out of hiding. Its comment says it returns properties as a JSON object, with a field for each key. In the API, its definition moves out of the unnamed namespace, to below JSON string, so other files can call it, and it's the loop it was, a key and its value for each property, between braces. Then a new file, export, starting with its header file. We include string, for the folder's path, Abseil's status, for a folder it can't write in, and the graph's header. Export takes the graph and the path of a folder, and returns a status. Its comment says what it writes into that folder. The nodes go in JSON Lines, a line of JSON for each node, with its id, name, label and properties. The relationships go in CSV, a line for each, with the ids of the nodes it joins and its type. In export, we include sys stat, for mkdir, cerrno, for the error a call leaves behind, fstream, for writing files, and string, then Abseil's status and str cat, and the API's header, for the JSON. Export makes the folder first, with mkdir, and when that fails for any other reason than that the folder exists, it says it can't make the folder. The comment over it says a folder that's there already, from an earlier run, is fine. Then it opens the two files, as output file streams, and when either won't open, it says it can't write in the folder. Then a loop goes over the nodes, from zero up to the count. The comment over it says why the nodes are in JSON Lines: each line is a JSON object of its own, so a reader can take the file a line at a time. Each line is an object with the node's id, then its name and its label, as JSON strings, and its properties, through Properties JSON. The relationships' file starts with a line of headings, from, to and type, the way a CSV file names its columns. Then a line for each relationship, from its record: the node it starts at, the node it ends at, and its type's name, between commas. A type is a single word, so none of them holds a comma. In main, we include export's header, and the usage gets a line for sg export, which takes the graph's folder and the folder to write into. Export to is the function that runs it, and its comment says it writes the graph into the folder, for programs that read it, such as a script that trains a model on it. It calls Export, and prints the error when there is one. Otherwise, it prints how many nodes and relationships it wrote, and the time it took, and it returns zero, as the other commands do when they're done. In main, the command's flag is called to folder, as export is a word that C++ keeps for modules, so it can't name a variable. It takes four arguments, and the check for a command gets it too. The CMake file gets export in the library, and its test in the test program. Export's test goes in a file of its own. It includes export's header first, then stdlib, for mkdtemp, which makes a folder with a name of its own, fstream and sstream, for reading the files back, string, Abseil's status, the graph's header, and GoogleTest. Read is a helper, and its comment says it returns the text of the file at a path, which it reads into a string stream. The test, Writes nodes and relationships for other programs, makes a lion, gives it a label, Species, and a status, vulnerable, and adds a relationship from the lion to Panthera. It makes a new folder in the test's temporary folder, exports the graph into it, and checks that the export went well. Then it reads both files back: the lion's line, with its label and its status, then Panthera's, with an empty label and no properties, each followed by a new line. And the relationships' file has its headings, then zero, one, and PARENT_TAXON, the relationship from the lion to Panthera.
8:16 Let's build it, with export in the library, and run the tests. All sixty-seven of them pass, the export's test among them. With the Wikidata graph loaded, let's export it into a folder called export. It writes all twenty-one thousand, eight hundred and thirty-four nodes, and the relationships, in a few tens of milliseconds. With head, the first two nodes are the classes, the birds, Aves, and the mammals, each with its properties, the taxon's name and its Wikidata id. And the first relationships go from the orders of birds up to Aves, which is node zero.
GraphSAGE
8:51 The network lives in a script, gnn, next to the script that fetches Wikidata, as training is a job for Python, and for PyTorch, the library most people train neural networks with. Its docstring says what it does: it trains a small graph neural network on a graph that sg export wrote, a GraphSAGE, whose layers each give a node a new vector from its own and the average of its neighbours'. It learns which species are threatened, from their weights and from what's known about their relatives, and writes its predictions as facts, which sg load adds to the graph. Below that is how to run it: sg export writes the folder, uv runs the script, and sg load reads its predictions back. We import csv and json, to read the export, math, for logarithms, sys, for the arguments, and path, then torch, which is PyTorch, for tensors and training. Threatened is a set of the three statuses that the IUCN, the International Union for Conservation of Nature, counts as threatened: vulnerable, endangered and critically endangered. Not threatened is least concern and near threatened. The comment over them adds that a species listed as data deficient, or not assessed, has neither. Layers is four, and its comment says why: four layers reach four hops, from a species through its genus to its family, and back down to the family's other species. Hidden is the size of the vectors between the layers, thirty-two, and epochs is how many times the training goes over the graph, three hundred. Load opens the two files the export wrote, and reads the nodes, a JSON object a line, and the relationships with a CSV dict reader, which names each row's fields from the line of headings. As its docstring says, it returns the nodes, and the relationships as two lists of node ids, the starts and the ends. Graph sage is the network, a PyTorch module. Its docstring says what it holds: layers that each give each node a new vector, from its own vector and the average of its neighbours', and an output that turns the last vector into a score. Its constructor works out the sizes, the features first, then the hidden size for each layer. Each layer is a linear layer, a matrix of weights and a bias, and it takes twice the size it's given, as it gets the node's vector and its neighbours' average side by side. The output is a linear layer from the last vector to a single number. Forward is where the messages pass, and for each layer, each node adds up the vectors its neighbours send it, with index add, which adds each sender's row into its receiver's row, and divides by how many there are. The comment over it says that, in words. Then the node's vector and that average go side by side, through the layer, and through ReLU. After the last layer, the output gives each node its score. AUC measures how good the scores are, and its docstring says how: the area under the ROC curve, the chance that a threatened species scores higher than one that isn't, a half for a guess and one for no mistakes. It sorts the species by score, adds up the ranks of the threatened ones, and turns that sum into the share of pairs in the right order, with the formula of the Mann Whitney test. Main reads the folder and the output's path from the arguments, and loads the export. Senders are the starts and then the ends, and the comment over them says why: messages go both ways along each relationship, from parent to child and back. Receivers are the ends and then the starts, so each relationship carries a message each way. Degree is how many neighbours each node has, at least one, so a node with none doesn't divide by zero. Status is each node's status, when it has one. The comment over it says what comes next: the species with a status that says whether they're threatened, and the answer for each, one for threatened. Species is the list of those nodes, and ids holds them as a tensor. Answer is one for threatened, and zero otherwise. It prints how many nodes, species and threatened species there are. Set num threads gives PyTorch a single thread, and the comment over it says why. With more, the order a sum is added up in can change from run to run, and floats round differently in each order, so each run would train a slightly different network. Torch manual seed fixes the random numbers, so each run splits the species alike. The comment over it says what the parts are for: a random seventy percent to learn from, fifteen to pick the best epoch with, and fifteen to test on, which no choice is made with. Then the features each node starts with, a tensor of two numbers for each node, all zeros to begin with. Base is each node's own features, and its comment says what they are: its weight, on a log scale, as weights run from grams to tonnes, and whether it has one at all. For each node with a weight, the log of its grams goes in, divided by six. So the humpback whale, the heaviest with a weight here, comes out a little over one, and a one beside it says it has a weight. Features adds two more to each node, threatened or not, for the species in known, and zeros for the rest, as its docstring says, which is the label trick. The model takes four features, and Adam is the optimiser, which moves each weight a little each epoch, against its gradient. For each epoch, half of the training species show their answers, and the network learns to predict the other half, so it can't copy a species' own, which is what the comment over the shuffle says. The scores come from the network, with the shown half's answers as features. The loss is binary cross entropy on the hidden half, which is small when a threatened species scores high and one that isn't scores low. Zero grad, backward and step are PyTorch's three steps: clear the gradients, work them out, and move the weights. No grad turns the gradients off, as nothing is learnt there. Its comment says what comes next: each epoch is scored on the validation species, with each training answer shown, and the best epoch's weights are kept. The scores come from the network, with all the training answers as features, and the validation AUC is the AUC of those scores on the validation species. When the validation AUC beats the best so far, it keeps a copy of the weights, and each fiftieth epoch, it prints the loss and the validation AUC. Once training is done, the best weights go back in. Then comes a rule to compare with, and the comment says it's written by hand. It's the share of threatened species among the training species of a species' genus, and of its family, each with two made-up species at the overall share, so a small genus doesn't decide alone. Parent maps each node to the node its relationship goes to, its parent taxon. Share counts the threatened and all the training species in each group, and gives each species its group's share, with a lambda that says which group a species is in. The rule takes the average of the genus's share and the family's. Labels are the test species' answers, as zeros and ones. With the gradients off, the network scores each node, with each training answer shown. On the test species, it prints the rule's AUC and the network's, which is the comparison that counts, as neither has learnt anything from those species. Last, the risk, and its comment says what's written: the risk of each species the network didn't learn from, from zero to a hundred, as facts, a node's name and the property in braces. Learnt is the set of the training species' ids, as a set answers whether it holds an id without going through a list. The sigmoid turns a score into a chance between zero and one, which is multiplied by a hundred. Then it opens the output for writing, and goes through the nodes. Each species outside the training set gets a line, its name in brackets, with its risk in braces, rounded to a whole number, as our properties are whole numbers or strings. It counts the lines, and prints how many it wrote. And git ignores the export and the predictions, which a run writes into the repository's folder.
Training
16:42 With the Wikidata graph exported, let's train it, with uv running the script with PyTorch and NumPy, which PyTorch looks for. It takes about ten seconds, on a single thread of this machine's processor. Of about sixteen and a half thousand species with a status, about twenty-seven hundred are threatened, about one in six. At each fiftieth epoch, the loss goes down a little, and the validation AUC climbs from about zero point seven two to about zero point seven four, where it levels off. On the test species, the rule we wrote by hand scores zero point seven two nine, and the network zero point seven three four, a little higher. Then it writes the risk of about six thousand species, those it didn't learn from.
What it learnt
17:27 I think the honest reading is a modest one. The rule is a few lines of counting, the share of threatened species in a species' genus and family. The network does about as well, a little better on these species, after three hundred epochs of training. So what it learnt is close to what the rule says: that relatives share their risk. Nobody told it about genera or families, and it found that out from the relationships and the statuses. A network earns its keep where nobody can write the rule down, with many features and many kinds of relationships, and our graph has one kind and a weight.
Back in the graph
18:04 The predictions are facts, a species' name and its risk in braces, which is the format sg load reads. Loading them into the graph gives each of those species a risk property, without touching anything else. Now Cypher can ask for the species the IUCN lists as least concern that the network rates at a risk over seventy. There are fifteen, such as the common ostrich, two civets, Allen's swamp monkey, and the Japanese macaque, whose relatives are mostly threatened. And among the species listed as data deficient, which nobody has been able to assess, the network rates eleven over sixty, with two dwarf lemurs rated highest, whose genus has eight other species, each of them threatened. Keep in mind that a risk here is a model's guess from relatives and weight, while an assessment counts the animals and maps their range. So it's a list of species to look at more closely, nothing more.
What's missing
18:57 Our network leaves a lot out, and here's some of what it doesn't do. Its own features are a weight and whether there is one, where a species' diet, its range or its habitat would say more. Its graph has a single kind of relationship, PARENT_TAXON, where a knowledge graph has many, and networks such as relational graph convolutions learn a set of weights for each kind. The SAGE in GraphSAGE stands for sample and aggregate: on a big graph, it averages a sample of each node's neighbours, in batches, where ours averages all of them, all at once. Neo4j's library trains inside the database, and writes back from there too, where ours goes out to a script and back in through sg load. And keep in mind that this is a vanilla version of what the Graph Data Science library offers, built for graphs far bigger than ours, while ours is there to show how it works.
Wrap-up
19:47 So, today smollerGraph's graph went out to a graph neural network, and came back with a prediction for six thousand species. sg export wrote the nodes as JSON Lines and the relationships as CSV. A GraphSAGE of four layers, in PyTorch, passed messages along the relationships, four hops deep, and with the label trick, it learnt which species are threatened from their relatives, about as well as a rule written by hand. Its risks went back into the graph with sg load, for Cypher to ask about.
20:18 This is going to be an evolving project, so I'd love to hear from you. Let me know in the comments what you'd ask a network to predict on a graph of your own, and if you'd like to follow along, subscribe to the channel. I hope you find this useful, and thanks for watching.