Graph-Native Machine Learning
local graph
Chapter 7 — Graph-Native Machine Learning
Section titled “Chapter 7 — Graph-Native Machine Learning”In this chapter, you’ll learn about the intersection of graphs and ML. You’ll see how ML techniques can automatically enrich an existing knowledge graph as well as how to mine features from a knowledge graph to create accurate predictive models.
This chapter builds on the skills you learned in Chapter 6, where you exploited the topology of a knowledge graph by using graph algorithms. In doing so, you discovered useful insights like the shortest paths between nodes and revealed the communities within the knowledge graph. The same skills, using Neo4j Graph Data Science, Cypher, and Python, will again be called to action in this chapter. You will build on those skills and learn how to add graph-native machine learning to your toolbox to create models that can enrich your knowledge graph.
Like Chapters 3, 5, and 6, this chapter is not intended to be a comprehensive guide to graph-based ML. But it gives you enough information to begin to use knowledge graphs as the basis for ML, with sufficient detail to enable you to explore further should you choose.
Machine Learning in a Nutshell
Section titled “Machine Learning in a Nutshell”ML is a huge area of research and practice. But at its most abstract level, it is about deriving programs from data, and of course knowledge graphs are excellent data.
Traditionally, most software has been written to take some input and apply a function to produce some output data. The function is written by an expert human, often with a deep understanding of the domain. The function is usually a sophisticated program, which may require a team of professionals to build and maintain. Those people must handle all the potential edge cases and intricacies of the model so that its outputs remain high quality.
ML inverts these responsibilities. In training an ML model, the inputs are data and prior outputs while the output is essentially a program. The ML system learns what the program should do by cleverly correlating input and output data to create a new function or rule. Periodically, the model may be retrained as new data becomes available to ensure its output remains high quality.
The kind of program produced through ML depends on both the problem being solved and the preferences of the team that owns the problem domain. The program could be a statistical regression where historical data is mapped to a curve whose function has been determined by analyzing historical data so that future data points can be calculated. It could be a neural network (which underpins most deep learning approaches) where a program is trained over time to recognize or classify inputs (such as images) by creating a layered, linked network akin to a biological brain. It might also be a geometric learning system that can understand, which extends deep learning into the multidimensional topology of graphs.
The choice of model is an expert decision, but fueling that ML with knowledge graphs typically makes good sense. There are two ways you might choose to integrate graphs and ML:
- To predict how a knowledge graph will evolve over time, known as in-graph machine learning
- To extract features from the knowledge graph to build a high-quality external predictive model, known as graph feature engineering
Irrespective of which methods are used, the systems surrounding the ML model and knowledge graph are often arranged in a feedback loop. This means use of the model ultimately enriches the knowledge graph, which is then used to improve the model.
Topological Machine Learning
Section titled “Topological Machine Learning”In-graph machine learning is a collection of techniques where the knowledge graph can be enriched by computing over itself. The process searches for opportunities to add missing relationships, node labels, and even properties.
With graph-native ML, you can execute algorithms using your knowledge graph’s topology and data to gain insight. For example, using the built-in Neo4j movie knowledge graph (https://oreil.ly/DQ34o) as your basis, you can immediately use topological link prediction algorithms. Start by running the Neo4j Browser on an empty database, then enter :play movie graph to start the built-in tutorial to build a small knowledge graph of movies, actors, and directors. Browsing around the graph centered on Keanu Reeves, you can see that he’s had a busy career, including acting in all of the Matrix movies, as shown in Figure 7-1.
Figure 7-1. Keanu Reeves’s acting career
In a real-world knowledge graph, you know that things are imperfect. Some data is missing, some has been mishandled, and some you don’t even know about yet. While even imperfect knowledge graphs are useful, it is valuable to be able to use tools to increase the quality of the data. This is quite possible with graph data science, of course. To demonstrate topological link prediction, just delete a relationship you know exists and watch the algorithm recommend its re-creation. Remove the relationship between Keanu Reeves and the movie The Matrix, as shown in Example 7-1.
Example 7-1. Perturbing a knowledge graph to set up an algorithmic experiment
MATCH (:Person {name: 'Keanu Reeves'})-[r:ACTED_IN]->(:Movie {title: 'The Matrix'})DELETE rYou know that the ACTED_IN relationship between Keanu Reeves and The Matrix should have a high probability of existing—after all, you just deleted it! This is easily tested by running a topological link prediction algorithm like preferential attachment by Barabási and Albert (https://oreil.ly/JKXTd). Executing the algorithm can be done directly on the knowledge graph, as shown in Example 7-2.
Example 7-2. Invoking the Preferential Attachment algorithm on an actor and a movie to see if they should be linked
MATCH (Keanu:Person {name:'Keanu Reeves'})MATCH (TheMatrix:Movie {title:'The Matrix'})RETURN gds.alpha.linkprediction.preferentialAttachment(Keanu, TheMatrix, {relationshipQuery: "ACTED_IN"}) AS scoreRunning the code in Example 7-2 gives 28.0 as the score for the likelihood of Keanu Reeves having acted in The Matrix. This is a good indication that the relationship should exist, but it’s not emphatic. Using another topological link prediction algorithms might help to improve the score, depending on the nature of the graph, as can using a larger graph (at the expense of longer compute times). But another avenue of exploration is to train and use ML pipelines to solve the link-prediction problem.
Graph-Native Machine Learning Pipelines
Section titled “Graph-Native Machine Learning Pipelines”You can potentially improve link prediction (and prediction of labels and properties too) by moving to an ML pipeline. For this, you will need a reasonably large set of relevant training data from which features can be extracted by the ML pipeline to train a predictive model.
Graph Feature Engineering
Section titled “Graph Feature Engineering”Feature engineering is the activity of identifying useful data that can be used to train an ML model. Traditionally, those features came from columns in relational databases and might be labeled age, gender, or postal code.
Graph feature engineering involves identifying and extracting data from a knowledge graph to be integrated into an ML model. Since knowledge graphs have a topology as well as data, this enables you to extract more and typically higher-quality features than would otherwise be possible.
Features are often generated by running a graph algorithm over the knowledge graph. For example, you might compute the PageRank or community of each node in a graph and use those as features. Equally, you might simply encode the topology of the graph directly as a (non-human-readable) feature using node embeddings. Either way, you increase the number and quality of features available for ML that can lead to better performing predictive models.
With traditional ML, a significant amount of data engineering can be needed to set things up. However, if we use Neo4j to host our knowledge graph, then we can simply declare ML pipelines into existence, with only a little data wrangling needed.
The construction of a pipeline for link prediction is as follows:
- Create a graph projection from the underlying knowledge graph.
- Declare the pipeline into existence.
- Add properties to the nodes in the graph projection containing values based only on the result of some computation on the relationships in the graph (e.g., by running one or more graph algorithms).
- Add one or more link features to create a feature vector for each node pair in the graph using the properties computed in the previous step using a combiner.
- Split the graph into disjoint test, train, and feature sets.
- Add model candidates (for example, logistical regression).
- Optionally estimate the computational requirements of the training phase to ensure your machines have enough memory.
- Train the model, including evaluation metrics to judge the quality of the trained model.
- If the model is deemed good enough via its metrics, then push it into production.
Instinctively, that seems like a lot of effort. But since the required functionality is already built into Neo4j, you only have to declare the configuration of the pipeline, rather than directly implement it. Working through an example illustrates this very well.
Recommending Complementary Actors
Section titled “Recommending Complementary Actors”You’ve already seen the movies knowledge graph in “Topological Machine Learning”. It’s a small knowledge graph intended for educational purposes, but it’s realistic enough for you to build a predictive model which can recommend actors that might work well together based on whom they have previously worked with.
The first step is a small amount of data wrangling. Take the existing movie graph and match where actors have acted in the same movie. Then connect each pair of actors who’ve been in the same movie with an ACTED_WITH relationship (direction is unimportant). This is the only pretraining data wrangling you’ll need, and it’s simple, as you can see in Example 7-3.
Example 7-3. Adding ACTED_WITH relationships to the movie knowledge graph
MATCH (a:Person)-[:ACTED_IN]->(:Movie)<-[:ACTED_IN]-(b:Person)MERGE (a)-[:ACTED_WITH]->(b)Once your knowledge graph is enriched with ACTED_WITH relationships, you can easily visualize the network of actors who’ve worked together in the Neo4j Browser tool, as shown in Figure 7-2.
Figure 7-2. Subgraph of actors who have worked together
Now you can create a projection of that knowledge graph. The projection, just as you saw in Chapter 6, forms the basis for subsequent ML. This is a single procedure call, as shown in Example 7-4. You have to provide the name of the projected graph (actors-graph). You also need to supply the labels of any nodes to be included (Person in this case) and any properties on those nodes (empty {} in this case). Finally, you need to supply the names of any relationships (ACTED_WITH) and their orientation (UNDIRECTED).
Example 7-4. Creating a projection of actors who have worked with other actors
CALL gds.graph.project( 'actors-graph',{ Person: {}},{ ACTED_WITH: { orientation: 'UNDIRECTED' }})The next step is to create your pipeline. This takes a single Cypher procedure call:
CALL gds.beta.pipeline.linkPrediction.create('actors-pipeline')Now you have to think about the node properties that will be used to train the ML model. You can choose existing node properties from the underlying knowledge graph, or you can create new properties by running graph algorithms over the data. In this case, the topology shown in Figure 7-2 is important, so you need to encode that topology as a node property that can be read by the ML stages of the pipeline.
Using a node embedding algorithm, which encodes a node’s local topology as a number, is a good choice here. Neo4j Graph Data Science has a handful of such algorithms, including Node2Vec and FastRP, which are potentially suitable. In Example 7-5 you can see how to configure the FastRP algorithm to calculate a node property called embedding on each of the nodes in the projection. Each property will be enriched with a numerical encoding of the node’s position in the topology when the pipeline executes.
Example 7-5. Configuring the pipeline to inject a node embedding property into all nodes using the FastRP algorithm
CALL gds.beta.pipeline.linkPrediction.addNodeProperty('actors-pipeline', 'fastRP', { mutateProperty: 'embedding', embeddingDimension: 256, randomSeed: 42})The next step is to configure the part of the pipeline that deals with link features. Recall that a link feature is a single feature that joins a node pair together and is a necessity for topological ML. The link feature steps will be executed both at training time when the pipeline runs and in production when the model makes predictions.
Example 7-6 shows how this can be done. The feature step is added with the addFeature procedure, which takes the name of the pipeline and an algorithm for determining whether a node pair should be joined. In this case, cosine has been chosen, which generates the cosine similarity (https://oreil.ly/EQGHb) of the embedding node properties defined in Example 7-5. If the vectors are close enough, they are considered to be linked. Other options for link feature algorithms include Hadamard product (https://oreil.ly/I-Kmv) and L2 (https://oreil.ly/s52qj). In this small use case, after some experimentation cosine appears to give the best results.
Example 7-6. Adding cosine (closeness) as the link feature that determines if two nodes are linked
CALL gds.beta.pipeline.linkPrediction.addFeature('actors-pipeline', 'cosine', { nodeProperties: ['embedding']}) YIELD featureStepsIn order to train and test the predictive model, positive and negative examples need to be fed into the pipeline. This is automated by the tooling, with the user only having to specify the fraction of the graph used for testing and the fraction of the test complement set (data not used for testing) that will be used for training. This is shown in Example 7-7. If you don’t want to tune the relationship splitting yourself, you can omit this configuration and use the defaults.
Example 7-7. Splitting the test and train data for the pipeline
CALL gds.beta.pipeline.linkPrediction.configureSplit('actors-pipeline', { testFraction: 0.25, trainFraction: 0.6, validationFolds: 3})The next step in configuring the pipeline is to add one or more model candidates. At the time of writing, the choices are:
- Logistic regression
- Random forest
- Multilayer perceptron
These models can be added to the pipeline with a procedure call like CALL gds.beta.pipeline.linkPrediction.addLogisticRegression('actors-pipeline'). The model (or models) registered are then readied for auto tuning with a single procedure call CALL gds.alpha.pipeline.linkPrediction.configureAutoTuning('actors-pipeline', {maxTrials: 100}). In that call, actors-pipeline is the name of the pipeline to be tuned, and maxTrials declares the maximum number of tuning iterations each model will undergo before choosing the best parameters. Note that on small models like this, the computational time is negligible on modern computers, but on a large ML pipeline, the processing time of each iteration could be many minutes.
The pipeline is now ready for training. But before you do that on a production-sized data set, it’s worth taking a moment to check the training memory requirements and, if necessary, running training on a machine with sufficient memory. The memory check is just a simple procedure call again, as shown in Example 7-8.
Example 7-8. Checking for sufficient memory to run the training task
CALL gds.beta.pipeline.linkPrediction.train.estimate('actors-graph', { pipeline: 'actors-pipeline', modelName: 'actors-model', targetRelationshipType: 'ACTED_WITH'})YIELD requiredMemoryOnce you’re comfortable with the memory requirements for training, you can proceed to train the model as shown in Example 7-9. The code in Example 7-9 instantiates a pipeline using the configuration that you provided earlier and executes the training phase, producing a model called actors-model as its output. It also yields some metrics (https://oreil.ly/-4fz-) about the training phase, which a data scientist can use to reason about the quality of the model.
Example 7-9. Running the training task
CALL gds.beta.pipeline.linkPrediction.train('actors-graph', { pipeline: 'actors-pipeline', modelName: 'actors-model', metrics: ['AUCPR'], targetRelationshipType: 'ACTED_WITH', randomSeed: 73}) YIELD modelInfo, modelSelectionStats
RETURN modelInfo.bestParameters AS winningModel, modelInfo.metrics.AUCPR.train.avg AS avgTrainScore, modelInfo.metrics.AUCPR.outerTrain AS outerTrainScore, modelInfo.metrics.AUCPR.test AS testScore, [cand IN modelSelectionStats.modelCandidates | cand.metrics.AUCPR.validation.avg] AS validationScoresOnce you have a trained model, you can use it to make predictions. The starting point for that is to feed in a graph projection on which the model can be executed. The input graph actors-input-graph-for-prediction shown in Example 7-10 is based on the original movie graph but with some perturbations that make it slightly different. Those perturbations are simple Cypher statements to add in a few more synthetic actors and delete a few ACTED_IN relationships. In a production scenario, you would use your real knowledge graph instead.
Example 7-10. Creating an input graph on which the model will make predictions
CALL gds.graph.project( 'actors-input-graph-for-prediction', { Person: {} }, { ACTED_WITH: { orientation: 'UNDIRECTED' } })The model can now execute on the input graph, as shown in Example 7-11. The parameters are somewhat self-explanatory:
actors-input-graph-for-predictionis the projection used as the input graph.actors-modelis the trained model produced by Example 7-9.relationshipTypesspecifies that the execution should only concern itself with processingACTED_WITHrelationships.mutateRelationshipTypespecifies that the execution should write backSHOULD_ACT_WITHrelationships into the projection when a certain confidence level is met.topNsets the number of recommendations required.thresholdsets the confidence level below which a recommendation is discarded. In this case, it’s a low threshold, since it’s a small-scale problem with an immediate human end user (the person who casts roles for actors). A real production system is likely to have a higher threshold to prevent too many low-quality predictions being produced.
Example 7-11. Writing results back to the graph projection
CALL gds.beta.pipeline.linkPrediction.predict.mutate( 'actors-input-graph-for-prediction', { modelName: 'actors-model', relationshipTypes: ['ACTED_WITH'], mutateRelationshipType: 'SHOULD_ACT_WITH', topN: 20, threshold: 0.4 })YIELD relationshipsWritten, samplingStatsOnce the code in Example 7-11 has executed, you are left with an enriched projection, but the recommendations have not yet been written back into the knowledge graph.
If you don’t want to persist the recommendations from your model, you don’t have to. Simply switch out the procedure call
gds.beta.pipeline.linkPrediction.predict.mutateforgds.beta.pipeline.linkPrediction.predict.streamand drop themutateRelationshipTypeparameter. Your results will now be streamed directly back to the user without enriching the projection.
You can see how this is achieved in Example 7-12. You stream SHOULD_ACT_WITH relationships from the actors-input-graph-for-prediction projection and then use some Cypher to take the source and target IDs from the streamed relationships and MERGE them back into the underlying knowledge graph.
Example 7-12. Persisting results in the knowledge graph
CALL gds.beta.graph.relationships.stream( 'actors-input-graph-for-prediction', ['SHOULD_ACT_WITH'])YIELD sourceNode, targetNode
WITH gds.util.asNode(sourceNode) AS source, gds.util.asNode(targetNode) AS target
MERGE (source)-[:SHOULD_ACT_WITH]->(target)An optional final step is one more piece of wrangling to tidy up the knowledge graph. Since SHOULD_ACT_WITH relationships are symmetric, there’s no need to have two of them between actors. That is, (a)-[:SHOULD_ACT_WITH]->(b) is sufficient, and you don’t necessarily need the reciprocal (b)-[:SHOULD_ACT_WITH]->(a). If you want to normalize the knowledge graph in this way, the Cypher code is presented in Example 7-13.
Example 7-13. Normalizing the knowledge graph
MATCH (a:Person)-[:SHOULD_ACT_WITH]->(b:Person)-[d:SHOULD_ACT_WITH]->(a)// Prevents a node matching as a first then b later, so deleting all relsWHERE id(a) > id(b)DELETE dOnce any wrangling is complete, the knowledge graph is enriched and ready for querying. A simple Cypher query like that shown in Example 7-14 is all that is needed to retrieve a set of recommendations. It just finds people connected by the SHOULD_ACT_WITH relationship that came from executing the predictive model over the graph and returns those people’s names.
Example 7-14. Querying the knowledge graph for complementary actors
MATCH (a:Person)-[:SHOULD_ACT_WITH]->(b:Person)RETURN a.name, b.nameAfter running Example 7-14, you’ll obtain results like those in Table 7-1.
Table 7-1. Recommendations for actors to work with other actors
| a.name | b.name |
|---|---|
| Naomie Harris | Emile Hirsch |
| Naomie Harris | John Goodman |
| Naomie Harris | Susan Sarandon |
| Naomie Harris | Matthew Fox |
| Naomie Harris | Christina Ricci |
| Danny DeVito | Demi Moore |
| Danny DeVito | Noah Wyle |
| Danny DeVito | Kevin Pollak |
| Danny DeVito | James Marshall |
| Danny DeVito | Christopher Guest |
| Danny DeVito | Aaron Sorkin |
| John C. Reilly | Demi Moore |
| John C. Reilly | Noah Wyle |
| John C. Reilly | Kevin Pollak |
| John C. Reilly | James Marshall |
| John C. Reilly | Christopher Guest |
| John C. Reilly | Aaron Sorkin |
| Ed Harris | Sam Rockwell |
| Lori Petty | Julia Roberts |
As these recommendations are persisted in your knowledge graph, you can reuse them and combine them into other queries, despite them being created by ML. Bear in mind that you’ll need to repeat this process periodically (hourly, daily, monthly) to keep the data fresh depending on your use case needs. Finally, remember this is just a starting point, and the real time is spent optimizing parameters for the model, especially around properties, features, and metrics for the trained model. While the auto ML can help, human intelligence is still needed to bootstrap artificial intelligence!
If the scope of the in-graph ML pipelines isn’t sufficient for your needs, you can always fall back on external tools like TensorFlow, PyTorch, and scikit-learn or cloud-hosted systems like Google’s Vertex AI, Amazon SageMaker, and Microsoft’s Azure Machine Learning. The bridge between the two domains is the set of feature vectors extracted from the knowledge graph which is used as input to train and test the externally hosted model. Through experimentation and iteration (either automatically or manually), it may be possible to use the greater depth of these tools and platforms to create better ML models, at the expense of implementation complexity, especially enriching the knowledge graph with the results from those external systems.
Implementing Graph ML with Rust and petgraph
Section titled “Implementing Graph ML with Rust and petgraph”If you are following the embedded architecture from previous chapters using petgraph and redb, you don’t have access to Neo4j’s built-in GDS pipelines. However, Rust’s high performance and rich ecosystem allow you to implement graph feature engineering and train external ML models very effectively.
The general workflow in Rust looks like this:
- Traverse the
petgraphto extract structural features (e.g., node degrees, clustering coefficients). - Export these features into a format suitable for ML (like an
ndarrayor CSV). - Train a model using a Rust ML framework like
linfaorsmartcore(or export to Python/PyTorch via FFI). - Run predictions and enrich the
petgraphdirectly.
Let’s look at a simplified example of how you might extract features and run a basic link prediction heuristic directly in Rust.
Example 7-15. Extracting graph features and running a heuristic link prediction in Rust
use petgraph::graph::{Graph, NodeIndex};use petgraph::Direction;use std::collections::HashSet;
// Assume our schema from previous chapters#[derive(Debug, Clone)]pub struct Person { pub name: String,}
pub fn predict_links(graph: &mut Graph<Person, ()>) { let mut new_edges = Vec::new(); let node_indices: Vec<NodeIndex> = graph.node_indices().collect();
// Iterate through all pairs of nodes for i in 0..node_indices.len() { for j in (i + 1)..node_indices.len() { let node_a = node_indices[i]; let node_b = node_indices[j];
// If they are already connected, skip if graph.contains_edge(node_a, node_b) || graph.contains_edge(node_b, node_a) { continue; }
// Feature extraction: Common Neighbors (a basic topological feature) let neighbors_a: HashSet<_> = graph.neighbors_undirected(node_a).collect(); let neighbors_b: HashSet<_> = graph.neighbors_undirected(node_b).collect();
let common_neighbors = neighbors_a.intersection(&neighbors_b).count();
// Simple heuristic prediction rule: If they share more than 2 friends, they should be linked if common_neighbors >= 2 { new_edges.push((node_a, node_b)); } } }
// Enrich the graph with the predicted links for (a, b) in new_edges { println!("Predicting link between {} and {}", graph[a].name, graph[b].name); graph.add_edge(a, b, ()); }}For more advanced ML, such as generating node embeddings (like Node2Vec or FastRP), you would typically implement a random walk generator over your petgraph structure, collect the walks, and feed them into a Word2Vec implementation (like the word2vec crate).
While you have to write more boilerplate compared to Neo4j’s GDS, executing these algorithms over an in-memory petgraph is incredibly fast, allowing you to train models on the fly within your Rust application.
Summary
Section titled “Summary”At this point in the book, you’ve covered enough of the technical details of building knowledge graphs to be competent. From creating and querying knowledge graphs, through applying graph algorithms, and finally using graph ML to enrich your data, you have covered a great deal of fundamental technologies. It’s no mean feat to have come this far, so well done! From here on, you’ll be applying your technical skills to specific knowledge graph use cases, starting with mapping the data in your enterprise.