link here


link here

This is a graph. A collection of dots joined by lines. The dots are called nodes or vertices and the lines are called links or edges.

Graphs are very useful, because they are a very versatile way of representing many things. In the context of this lecture, we will focus on graphs as data. That usually means that the nodes in the graph represent entities in the real world, and the links represent relations between them.

In this example, the nodes represent people, and the links express who follows whom on social media.

click image for animation
link here

If the links have a direction we call the graph directed. Examples of directed relations are: following someone on social media, owing somebody money, being someone’s parent and so on. If you reverse the arrow, the meaning of the link changes.

If the links don’t change meaning when you reverse them, we call the graph undirected. Examples of undirected relations that you could make a graph out of are: two cities being connected by rail, people being friends, people having met, and so on.

If an edge connects a link to itself, we call that a self-loop. Self-loops are sometimes impossible, like being your own parent, or always true, like being a your own family member. If they are always true, they are usually left out. There are however cases in which a self-loop is is useful to allow (that is, it is sometimes true): in a company graph of employees that connects people to the person that approves their expenses, some people may be allowed to approve their own expenses.

If there can be two or more edges between a given pair of nodes—for example to express different loans from person a to person b—we call that a multi-edge, and if this is allowed, we call the graph a multi-graph.

A graph that doesn’t have multi-edges or self-loops is called a simple graph (it can be directed or undirected).

link here

One particularly useful type of graph for representing data is a knowledge graph. In a knowledge graph, we have edges of different types, so that we can express different relations between entities. You can think of a knowledge graph as several graphs, each expressing a different relation, joined together.

You could do this with various types of graphs, but the most common rules for knowledge graphs are:

All links are directed.

Self-loops are allowed

Multi-edges are allowed but only of different relations. A single relation can only connect entities in one direction once.

We’ll put a special focus on knowledge graphs in this lecture, since they are so useful as representations of datasets.



link here

One standard way of representing a knowledge graph is the Resource Description Framework (RDF). This uses URLs for the entities and relations which allows different datasets to refer to the same entities in a coherent way.

RDF also allows “literal nodes” which can be used to encode non graph data like numbers, dates, natural language or images as special nodes in the graph. This makes RDF a particularly useful format for integrating different types of multi-modal data.

click image for animation
link here

link here

The adjacency matrix is a way to represent a graph as a matrix. Since matrices (and tensors more generally) are central to deep learning, the adjacency matrix comes up a lot.

The idea is simple, we put all the nodes in the graph along the rows and columns of the matrix. The order is arbitrary, but we need to use a fixed order.

Then, if node i is connected to node j, the element at (i, j) in the matrix has a 1, otherwise it has a zero. For an undirected graph, both (i, j) and (j, i) get a 1, so the matrix is symmetric. For a directed graph(i, j) only gets a 1 one if the connection is from i to j.

link here

We won’t discuss these in this lecture, but there exist graph neural network approaches for all of them.

link here

If you have a graph, these are the main abstract learning tasks you could want to perform on them.

link here

The aim of link prediction is to predict links that are missing from the graph. This could be because the graph is genuinely incomplete, but it could also be a good way to predict links that should be in the graph for some reason.

For example, if we train a model that thinks that Claire is likely to follow Don, then that would be a good recommendation for the social network to make to Claire.

click image for animation
link here

Link prediction in knowledge graphs is especially powerful. It’s like training a whole collection on classifiers and recommender systems in one go.

If we have just two types of nodes (say users and movies) and one relation (indicating whether the user liked the movie) then link prediction becomes movie recommendation. By expanding the knowledge graph we can include information about the users and about the movies.

click image for animation
link here

Node classification is another task: for each node, we are given a label, which we should try to predict.

If we have vector representations for our nodes, we can use those in a regular classifier, but the question is, how do we get those embeddings, and how do we ensure that they capture the required information?

We can’t just assign node embeddings like before, and apply gradient descent on the classification loss. That would ignore the graph structure entirely and would train each embedding in isolation to produce a particular clasification. We wouldn’t generalize between nodes.

link here

In many tasks (especially node classification) the nodes also come with feature vectors. These contain information about the nodes.

You could see these kinds of tasks as a generalization of basic tabular classification, except there are relations drawn between the instances. If you remove all links, then you get a plain old classification task.

link here

An alternative approach is to encode the information you have about the instances as part of the graph. This requires a knowledge graph.

This approach has many benefits. It can deal very neatly with missing data (you just leave it out) and you can model things like units for attributes in well-designed ways. The downside is that this puts more weight on the modelling task. Building models that can use this kind of graph well is ongoing research.

link here

Finally, you may have a labeling task where the label applies not to one node but to a whole graph. One example is the MUTAG dataset, where the task is to predict whether a particular molecule, represented as a graph, is mutagenic.

You can of course also do graph regression, where the task is to assign a number to each graph in the dataset.

link here


link here

The key idea of link prediction is to come up with node representations that can predict, for two given nodes, whether there is or should be a link between them. For example, if your graph is a friendship network, you could predict whether these two are or people should be friends. this prediction should be based on two vectors, representing the two people. These vectors are our node representations.

We then train our node representations to make this prediction as accurate as possible.

You can think of this as a surrogate task. Sometimes we are actually interested in predicting these links, but even if we aren’t, the resulting node representations can be used in other tasks, like node labelling.

We’re focusing here on link prediction methods that work by building embedding vectors for the nodes in the graph. There may be other ways to solve the problem, but this is the most popular family of approaches.

link here

This is similar to what we did for word embeddings. Words for a set for which we have no features. All we know about a word is that it is different from other words, and the same as itself (across places where it occurs). We assign each word an embedding vector, and then use these vectors in a task, which leads to a loss. We train to minimize the loss, giving us optimized embedding vectors as a result.

In the case of Word2Vec, the actual training task (predicting neighbouring words) was not something we were interested in: it was a proxy task to give us good embeddings.

Link prediction can be both: a proxy task, or the actual task we’re interested in.

click image for animation
link here

Assume we have a graph with N nodes. Our job is to generate N vectors representing these nodes. Or if we concatenate them, a matrix with N columns.

The dimensionality of the embedding vectors, k, is a hyperparameter that we (usually) set ourselves.

link here

To figure out how we might train these embeddings, imagine first that we had the resources to manually set features for each node in our graph.

We’ll stick with our example of a friendship graph. What features might tell us whether two people should be friends? Here we’ve gone with how physically active they are, how introverted they are, and politically conservative they are. We’ll assume (perhaps naively) that if these match between two people then they are more likely to make good friends.

Each feature is a number between -∞ and +∞. The score is also in the range (-∞, ∞).

What this shows, is that in this situation, where we have known features, the dot product is a good score to help us predict whether two people are, or should be, friends

click image for animation
link here

If we don’t have features, and instead want to learn the values of the embeddings, what we can do is take the dot product and train it to be high for pairs of connected people (friend) and low for pairs of unconnected people (non friends). If A is our adjacency matrix, we can use squared error for our loss and train the dot product to mimic the values in the adjacency matrix.

This objective is something we can minimize by gradient descent.

What’s wrong with this idea?

The dot product needs to mimic value between 0 and 1

assumes all values are known

link here

One common way to get scores that range from 0 to 1 is to model them as probabilities. We take the dot product of the two node embeddings and we pass it through a sigmoid function. We then interpret this as the probability that node a links to node b.

Once we have that, we can compute the log-likelihood of the data under our model parameters (all the embedding vectors) and use that as our loss.

click image for animation
link here

The next problem is that we often aren’t told which links are false. We will have lots of examples of people are friends, but we don’t have any examples of people who shouldn’t be friends.

The solution is to assume that the complete graph (of all the people who could ever be friends) is sparse. That is, for a random pair of people the probability is much higher that they should be friends than that they shouldn’t. Moreover as the graph gets bigger, the probability that two random people should be friends goes to zero.

If this is the case, then for a large graph, we can simply sample a random pair of nodes and treat it as a negative. Occasionally we’ll be wrong, but in the vast majority of cases, we’ll be right. Gradient descent is very robust to the occasional bit of noise so we can expect a good model.

link here

With a bunch of negative samples, we have everything we need to implement this loss function.

In the pseudocode, we sample one negative link for every positive link, but this proportion is a hyperparameter. Often, sampling many negative links is a strong strategy.

link here

link here

Link prediction is especially popular in knowledge graphs. This requires some extensions.

link here

Most centrally, link prediction now becomes triple prediction: we don’t need to predict just whether sandra and memento are connected, but we need to predict which relation connects them. In short we need a score function, as before, but now it has three arguments, the subject, predicate and object of the triple. It returns a score that indicates how likely the triple is.

If we have a goodscore function, that is quick to compute, we can ask queries. For example, for an incomplete triple like (sandra, likes, ?), we can check what goes best at the place of the question mark. We simply try every single node in the graph, compute the score of the triple for each, and then rank the nodes by their score. The node x for which (sandra, likes, x) gives the highest score is our best predicted answer to the query.

link here

Link prediction models are evaluated on the task of answering triple queries. We set the data up as a long list of triples, and then withhold a test and validation slice.

We build a score fuction s using the training data. Then on the withheld data, we pick a triple (s, p, o), withhold the tail (o) and use the score function to predict the what o was. We do the same for s, and see how well the model does.

More on the evaluation part later.

click image for animation
link here

To build an embedding model, we proceed as before: we create embedding vectors for the nodes in the graph. We also create embedding vectors for the different relations (the predicate).

click image for animation
link here

link here

link here

link here

link here

link here

link here

Where log loss takes inspiration from logistic regression, hinge loss takes inspiration from SVMs and the max-margin loss. In practice, it boils down to passing the raw score x through a hinge function max(x + m, 0) for negatives and - max(x + m, 0) for positives.

We then take the sign of the score as the prediction (a positive score is a positive triple).

This means that positives that get a very high score don’t count in the loss function. Only the ones that the model gets wrong (true triples with a negative score) or just right (true triples with a low positive score) do anything to the loss function. The mechanism is similar to the SVM in that only a few key examples end up determining the parameters of the model.

click image for animation
link here

link here

The pointwise hinge loss is shown, but you can do the same thing with a log loss.

link here

link here

link here

Think back to our movie recommendation example. Say we predict from user. movie embeddings by a simple dot product (the higher, the more likeley the user is to like the movie).

In that case, all the predictions we can make (i.e. all the dot product) for a matrix that we can calculate by multiplying the matrix of user embeddings by the matrix of movie embeddings as shown.

link here

It is important to carefully consider our validation protocol. In other words: how do we withhold test data to train on.

Let’s start with recommender systems. At first, you might think that it’s a good idea to just withhold some users.

However, this doesn’t work: if we don’t see the users during training, we won’t learn embeddings for them, which means we can’t generate predictions.

link here

How about if we withhold some movies? The same thing happens.

link here

link here

This is related to the difference between inductive and transductive learning. In the transductive setting, the learning is allowed to see the features of all data, but the labels of only the training data.

In short, when you have embedding vectors for entities in your data, you can only do transductive learning. The reason is simple: you cannot learn what to do for entities you’ve never seen before, because you won’t have trained their embeddings yet.

click image for animation
link here

link here

link here

In the case of node classification, we provide the algorithm with the whole graph, and a table linking the node ids to the labels. In this table, we withhold some of the labels. The model is however, aware of the nodes for which we’ve withheld the labels.

link here

link here

click image for animation
link here

Accuracy is rarely used, since most models get such low accuracy that we don’t get a very good signal of how well the models are doing relative to each other. However, it can help you understand what the other two metrics mean.

The diagram illustrates each metric for an imagined test set of 6 triples (checking only the tail corruption). We test the model and for each triple, find what the rank of the true triple is. This is given on the horizontal axis. The metric is then computed by taking the average length of the bars (with the tallest ones having length 1).

Note that this means that all metrics are values between 0 and 1. We can also conclude that the accuracy is always a lowerbound for the hits@k and for the mrr.

link here

link here

This paper is a good source for a detailed explanation of the knowledge graph link prediction protocol.

link here

link here

In the previous section we saw how to do link prediction with node embeddings. This is an interesting task in itself, but it can also be a good proxy task to train reasonable node representations that we can then use in a task like node classification.

In this section we’ll go a bit further, and focus on node classification by deep neural network.

link here

link here

By analogy with the sequence-to-sequence layer, we can design a graph-to-graph layer. We have a graph, with a certain number of nodes. Each node is represented by a vector. This could be an embedding vector, a feature vector, or the output of some process below this layer.

The layer operates on the graph, and produces new vectors representing the nodes. Ideally, like the (non-trivial) sequence-to-sequence layers propagate information over the time dimension, the graph-to-graph layer propagates information over the graph structure.

link here

link here

Here is the very simplest graph neural network we can build. The simple graph convolution. We start with node embeddings. Then the aggregation layer replaces each node embedding with the sum over the embeddings of all the neighbors of that node. Then we apply a simple linear layer, and a non-linearity.

link here

link here

link here

link here

link here

Remember that we should be on the lookout for activations blowing up. If we sum together the vectors for a node with five neighbors, then the output activations will be five times as big as the input activations.

To fix this, we can simply replace our sum layer with an average.

link here

To write this in a matrix view, we create a degree matrix D. This is just a diagonal matrix with the degrees of the nodes along the diagonal. The inverse of a diagonal matrix just has 1/d where the original matrix has d, so D-1 gives us all the values we want to multiply by along the diagonal.

If we multiply D-1 by A then we then we are row normalizing the adhjacency matrix. That is, all the values in one row sum to one. After row-normalizing, multiplying by the adjacency matrix computes precisely the average we are looking for.

click image for animation
link here

Of course, we don’t just care about keeping the activations in check.

We know from previous derivations that if Y is computed by the matrix multiplication AX, then the gradients for X are computed by mutiplying the gradients for Y by the transpose of A.

This tells us that if we row-normalize, as we did in the last slide, we can end up shrinking and blowing up the gradients. In the example, we are multiplying the incoming gradient vectors for node 2 by 1/2 and 1/5, which sums to less than one. For node 3, the weights sum to 4!

We can fix this by column-normalizing instead.

click image for animation
link here

We achieve column normalization simply by right multiplying the inverse degree matrix.

With column normalization, the gradients propagate perfectly, but of course now we have a problem with the activations: they can now shrink and blow up as before.

For directed graphs, we often just row-normalize and call it a day. If the network isn’t too deep, the gradients should still propagate.

For undirected graphs however, it’s more common to do a kind of mixture between row and column normalization.

click image for animation
link here

The trick is to break D-1 up into two matrices that give you if you multiply them together. This is easy to do with diagonal matrices, since multiply them is just element-wise multiplying the diagonal elements. That means that if we take the square roots of the diagonal elements (D-1/2), we get D-1 back.

We can now row normalize “a bit” and column normalize “a bit” by premultlying by the square root degree matrix and post-multiplying by it.

This gives us a bit of control over the activations blowing up and over the gradients blowing up. The weights are not fully normalized in the row or column direction (you can check that they never sum to one) but their sums should never sum a value that is too far below or above 1.

link here

Which operations can we use for aggregation?

link here

We can think of the aggregation step as taking the current node representation, and mixing in some of the representation of the neighbors. We usually don’t want to throw the current representation of the current node away, however, we just want to add to it.

To achieve that, we should include the current node x among its own neighbors N(x). Or, equivalently, we should assume that each neighbor has a self-loop.

Often, the self loops are given their own separate weight matrix V. This allows the network to treat the information propagating over the self loops differently from the information coming in from the neighbors.

You can think of this as applying two GCNs: one for the regular graph, and one for the self loops.

click image for animation
link here

Here’s what a 2-layer node classification GCN looks like step by step, with the self loops in place.

click image for animation
link here

We can extend this idea to allow us to handle knowledge graphs. We simply apply a separate GCN for each relation, each with its own weight matrix. and then sum together their outputs. before applying the non-linearity.

We can now treat the self loops as just another relation (the “identity” relation).

We also normally include all inverse relations: if there is an arrow from a to b with relation r, we add an arrow from b to a with relation r-1.

The reason for the inverse links is that in a directed GCN, the model passes information along the direction of the node. However this direction doesn’t usually mean that information only flows in one direction. It just indicates which node is the object and which node is the subject. We could let information flow in two directions, but that would be like making the graph undirected. Ie.e removing information. By creating inverse relations, information flows in two directions, but the information of the edge directions is retained.

In short, if we are given a knowledge graph with R relations, our RGCN has 2R + 1 relations (we don’t add an inverse link for the identity).

click image for animation
link here

RGCNs with many relations are prone to overfitting, because they have a large number of weights (the double descent phenomenon has not been observed yet in GCNs).

One way of regularizing them is to make the weigh matrices not free weights, but linear combinations of a small number of basis matrices. The picture shows the idea for two basis matrices V1 and V2.

link here

We can define a whole family of GNNs by alternating two types of layers. One that propagates information over the graph, and one that computes locally on the individual node embeddings. These are called aggregate and update. So long as we make sure that aggregate is permutation equivariant and update is local (i.e. pointwise), we can pick any function we like.

This is called the message passing framework. The idea is that the neural network computes its function by passing messages aling the links of the network.

link here

link here