Pattern Detection Knowledge Graphs
local graph
Chapter 10 — Pattern Detection Knowledge Graphs
Section titled “Chapter 10 — Pattern Detection Knowledge Graphs”Managing enterprise data as a knowledge graph provides plentiful benefits. Data is (logically) centralized, curated, and contextualized. A knowledge graph can be mined for patterns that originate from interesting business events. Those patterns give historical insight into the business, but they can also be used to look forward.
This chapter focuses on finding patterns in knowledge graphs and using those patterns to improve future outcomes. Starting with simple pattern-matching approaches, you’ll see how the patterns in your knowledge graph can be easily exploited to stop fraud and build better teams. In each of the use cases, you’ll also see how pattern detection can be augmented by graph data science to enrich the knowledge graph and surface new, valuable patterns.
Fraud Detection
Section titled “Fraud Detection”Online fraud is a widespread and pernicious problem in the era of ubiquitous computer systems. These systems host some of the most critical aspects of our personal lives and are the lifeblood of modern businesses. They are tempting targets for criminals who might want to defraud individuals or organizations.
The level of that temptation is eye-watering. In the United States alone, fraud cost the productive economy 1 billion being lost in the banking sector alone. Worse, the amount of money lost to fraud is increasing at a staggering 70% year on year. The picture is similar in other advanced economies, with the United Kingdom’s banks losing around £700 million ($856 million) to fraud.
But it gets worse. For each 4.21 (four times more) is lost dealing with attacks and liabilities, loss of reputation with customers, and the general work involved in trying to defend, contain, manage, and redress fraud. It is an expensive problem that necessitates a continuous arms race.
Even marginal improvements in fraud detection bring huge benefits in absolute dollar terms. Fortunately, knowledge graphs are an excellent platform upon which to mount your defense against fraudsters.
First-Party Fraud
Section titled “First-Party Fraud”Take credit cards as an example. For many of us, they are a necessary and useful part of modern life, but for fraudsters they’re a tantalizing opportunity. The value being transacted is huge, and the volume of transactions across cards and providers can provide enough cover for them to hide while leeching money out of the system.
In Figure 10-1, you can see the recent purchases of a credit card customer. Some transactions have been queried for possible fraud, and there is even a declined transaction in the recent history. This happens to all of us from time to time because the systems that process payments are imperfect and human behavior is erratic. Sometimes you really do want to spend thousands of dollars on a laptop, and sometimes you are making payments in a foreign currency because you’re on vacation. Sometimes your card has been stolen and a criminal is spending on your card without your permission. With the information available, it’s hard to know if this is a good customer, a customer in distress, or a fraudster.
Figure 10-1. Data in tables obfuscates structure, making it hard to distinguish between customers and fraudsters
Traditionally, finance companies have used rule-based strategies, such as assigning risk scores by searching for certain words, accounts, and locations. Alerts can then be sent to fraud analysts for manual review. This solution is slow, expensive, and inflexible. Conversely, using a knowledge graph to understand customers’ broader connected context provides a great deal more insight at scale.
Uncovering Fraud from Data
Section titled “Uncovering Fraud from Data”Loading the tabular data from Figure 10-1 into a knowledge graph is the first step in getting value from it. Figure 10-2 shows a better view of the same customer, which exemplifies the graph data model chosen. The credit card, with its unique card number, is at the center of each subgraph. It is surrounded by purchases made WITH the card, and each Purchase has a NEXT relationship to create a purchase history. The customer is connected to the card via an ACCOUNT_HOLDER relationship and also LIVES_AT an address and OWNS a phone number. They exist in their own disconnected subgraph, with no addresses or phone numbers held in common between customers.
Figure 10-2. A graph data model for a customer’s credit card history
Zooming in on one customer isn’t enough to validate the knowledge graph, and it is time consuming to do this for all customers. If the data seems to be as uniform as Figure 10-2, you should be able to verify that uniformity with some simple tests.
One way of coming to grips with a data set that isn’t entirely known is to verify some of its general qualities. An obvious starting point is to query for the number of people in the graph, as shown in Figure 10-3, to see if it matches the number of subgraphs.
Figure 10-3. Count of people in the Customer-Purchases knowledge graph
In Figure 10-3 you can see that there are 2,399,999 Person nodes in the graph. If the model is regular, like in Figure 10-2, then there should be 2,399,999 communities in the graph, one for each detached subgraph. You can check that with a community detection algorithm from Neo4j Graph Data Science, which you first saw in Chapter 6. Start by creating a projection on which to run the community detection algorithm, as shown in Example 10-1.
Example 10-1. Create a projection of people and their means of contact
CALL gds.graph.project( 'fraud-wcc', ['Person', 'Phone', 'Address'], ['LIVES_AT', 'OWNS'])The procedure call in Example 10-1 creates an in-memory projection of some elements of the knowledge graph. In this case it takes Person, Phone, and Address nodes along with LIVES_AT and OWNS relationships. It takes no property data or other nodes or relationships. The projection needs a very short time to prepare, and then you are ready to run one of the community detection algorithms, as shown in Example 10-2.
Example 10-2. Run the Louvain algorithm to compute communities in the graph
CALL gds.louvain.stream('fraud-wcc')YIELD Node, communityIdWITH gds.util.asNode(Node) AS person, communityIdSET person.communityId = communityIdExample 10-2 uses the Louvain algorithm to detect distinct communities in a knowledge graph. In this case, its job is simple because there should be 2,399,999 people in disjoint subgraphs, which should become 2,399,999 communities. For each community, the query takes its ID and writes it as a communityId property into each Person node in the community. But as you can see in Figure 10-4, things don’t quite tally up. There are only 1,803,467 community identifiers in the knowledge graph, around half a million too few.
Figure 10-4. Fewer communities than people in the knowledge graph
What Figure 10-4 tells you is that some communities must contain more than one person. It would be interesting to know more about those communities since they may or may not be benign.
Fraud Rings
Section titled “Fraud Rings”To understand what’s happening, you need to sample the graph. You can easily craft a query to drill down into communities that have more than one Person node and inspect them, as shown in Example 10-3.
Example 10-3. Sampling query to check why Person nodes might be linked
MATCH (:Person) WITH count(*) AS countMATCH (a:Person)-[*2..4]-(b:Person)WHERE rand() < 10.0/countRETURN aExample 10-3 starts by matching all Person nodes in the graph and providing a count of all items. It then matches paths between Person nodes at depth 2 to 4, so that we don’t match on small, well-behaved subgraphs. The query then chooses to include, or not, the current match based on a random number so that you get a sample of the knowledge graph rather than the full version.
Running the query in Example 10-3 yields the results shown in Figure 10-5 in which there are two disjoint and dissimilar subgraphs. They’re both quite different from the common pattern of a single person owning a phone and a credit card, living alone at a single address.
Figure 10-5. Reviewing a sample of the graph
But are the patterns in Figure 10-5 fraudulent? They are certainly different from each other and the expected form. Here you need subject matter expertise, at least to bootstrap that decision. For example, an analyst might observe a strong correlation between several short, consecutive Uber rides or a burst of expensive similar transactions, both suggesting a stolen or cloned card (or a phone on which the card is hosted).
In this case, the small subgraph is a household with a shared phone number and shared address. It’s reasonably common and is unlikely to be fraudulent. The larger subgraph is unlikely to represent ordinary customers; it is probably a fraud ring that has created synthetic identities anchored with real addresses and phone numbers. Knowing these patterns (and indeed discovering others through human expertise and machine learning) allows you to check for them as transactions are processed in a payments system and reject those that match.
But you can go further than that. If you find a fraudulent pattern, then it’s simple with a knowledge graph to traverse all of it to find all cards or accounts that might be compromised. To illustrate, take a step back and try to think like a fraudster.
Stealing cards must be stressful (though no sympathy for the fraudsters is necessary). The rightful owner tends to find out very soon that the card is missing or compromised and can act to cancel it quickly, perhaps even before any theft has taken place. As a criminal, it’s far better to own a card (or other lines of credit like bank accounts with an overdraft) in good faith so that you can take your time planning your fraud and maximize the haul. Simply operate the account normally, and you will often be rewarded with higher lending limits. This vertically increases the gain from the eventual fraud. Better still, you can horizontally scale your crime by creating compelling fake identities to gain access to many lines of credit. Then operate them normally until it’s time to commit fraud at scale.
The fraud-ring pattern is hard to spot with conventional data technology, but with a knowledge graph it becomes much easier. The pattern repeats, from a Person via a shared PhoneNumber to another Person to a shared Address to another Person to a shared PhoneNumber and so on, encompassing an entire fraudulent network. You can see this pattern clearly isolated in Figure 10-6.
Figure 10-6. A repeating pattern indicative of a synthetic identity fraud ring
Example 10-4. Cypher code for finding fraud rings in a knowledge graph
CALL { MATCH ring=(p1:Person)-[:OWNS|LIVES_AT*5..]-(p2:Person) WHERE p1<>p2 RETURN ring} IN TRANSACTIONS OF 100 ROWSRETURN ringOn a large knowledge graph, the code in Example 10-4 may take many seconds or minutes to execute. That’s OK since it’s an analytical query run periodically (e.g., hourly, daily) to highlight unusual customer patterns.
Allowing synthetic identities to grow permits fraudsters to build a substantial aggregate credit line. Once the fraudsters have built their criminal empire as big as they dare, they will cash out by rapidly using all the credit facilities at their disposal. Without a knowledge graph, the cash-out can appear to be random and unstoppable. Lines of credit are drawn down and left unpaid. When letters or debt collectors are sent to the synthetic identities, they are unanswered or, worse, affect genuine people who happen to live at those addresses. The money is lost.
With a knowledge graph, a cash-out in one part of a ring structure can be used very rapidly to find all other accounts in that structure and block or scrutinize transactions for those identities. This is a cheap operation since only a few hundreds or thousands of linked records need to be considered and can be performed in the transaction flow if necessary.
Innocent Bystanders
Section titled “Innocent Bystanders”You know now that in the sample in Figure 10-5, the larger subgraph is likely to be a fraud ring. But the other subgraph seems more benign. Not all linked identities may be fraudsters, since people legitimately share addresses, and even in modern times, people may also share phone numbers (especially landlines at their home address or place of work). Branding a household as fraudulent usually isn’t the right thing to do, and so in this use case you have to be aware of the pattern shown in Figure 10-7.
Figure 10-7. A household can share both a phone number and an address
Finding these patterns is a straightforward process—it’s actually a simplified version of the fraud-ring query with a specific path length. In Example 10-5 the MATCH query pattern matches against two people who live at an address and share a phone. Note that the variable p is used to ensure that the same person LIVES_AT an address and OWNS the same phone as the other anonymous Person.
Example 10-5. Cypher code for finding legitimate households in a knowledge graph
MATCH households=(p:Person)-[:LIVES_AT]->(:Address)<-[:LIVES_AT]-(:Person)-[:OWNS]->(:Phone)<-[:OWNS]-(p)RETURN householdsThe Cypher query in Example 10-5 is simple, though the MATCH clause takes a little unpacking. It returns paths of all households that fit the pattern of two Person nodes connected by two LIVES_AT relationships to an Address node and then connected via an OWNS relationship to the same Phone node. The first person matched is stored as variable p, which is used to end the pattern to ensure it’s the same person connected to the shared address and shared phone. Running this query for the current transaction in your payments system gives rapid confirmation that the holder is in a regular household. Another check is passed, and so confidence in the legitimacy of the transaction is increased.
Operationalizing the Fraud Detection Knowledge Graph
Section titled “Operationalizing the Fraud Detection Knowledge Graph”At this point, you understand some positive and negative patterns for fraud. In a production deployment, these patterns would be surfaced by subject matter experts, who can use their own knowledge and experience, supported by graph algorithms, graph machine learning, and visualization, to maintain a robust arsenal against fraud. Matching these patterns against a card’s subgraph is the key to operationalizing this kind of knowledge graph.
In general, you will prefer subgraph-local operations since they are very low latency. Because the data is stored in a knowledge graph of cardholders, it’s fast to access the subgraph centered on each customer during a transaction. It’s therefore possible to search the customer subgraph for suspicious patterns as customers are making purchases, since a relatively small number of records need to be considered. Doing so adds minimal latency during a purchase and, if you have a good understanding of fraudulent patterns, offers good protection.
In cases of particularly high risk or value, you might decide to run more intensive pattern matching across a larger area of the graph. Or you might even choose to run some data science processes over a subgraph. Since these may add many milliseconds or even seconds to your decision making, they should be used relatively sparingly; with the low-latency pattern matching handling much of the work. Using both subgraph-local pattern matching with occasional graph algorithms can be an effective way to turn your knowledge about your customers into a way to protect yourself, and them, from fraud.
Case Study: Banking Circle
Banking Circle (https://oreil.ly/kG4sJ) has a fraud management solution similar to that described in this chapter. At its core is a knowledge graph of accounts connected to payments. Banking Circle then uses community detection to generate features for its ML pipeline that detects high-risk clusters of customers. The knowledge graph topology is a critical input to the ML pipeline, combining graph features such as risk scores of near neighbors, distances to tax havens, and known fraudsters. It has had significant positive impact on Banking Circle’s fraud detection efforts. It has turned a slow and manual process into a scalable, flexible solution that can evolve to meet the ever-changing challenges that fraudsters present. Today, Banking Circle continues to experiment with graph algorithms and plans to add more graph features to further tune its predictive model.
Skills Matching
Section titled “Skills Matching”An organization that can recruit and retain skilled workers has an edge in the marketplace. But skilled workers, in all fields of human endeavor, require active support so that their skills continue to align with the organization’s ongoing needs. If an organization has the ability to recruit and retain skilled workers, the challenge of successfully deploying those workers into appropriate departments or projects remains. Not only do departments or projects require a specific mix of skills, but they also need different levels of seniority and experience. The best-run departments or projects will also have a diverse set of participants who (mostly) get along well.
Building robust teams is no trivial task, but knowledge graphs can help. There are many dimensions to building high-performing teams:
- Organizational chart, including cost centers and locations
- Expertise
- Project history
- Social engagement
- Tertiary skills (e.g., language)
Each of these can be modeled as a separate layer in a knowledge graph and brought together at query time to answer sophisticated questions. Those questions will help create and manage effective teams.
Organizational Knowledge Graph
Section titled “Organizational Knowledge Graph”The most obvious place to start to look for skills is the organizational (org) chart. As well as positional hierarchy, the org chart often identifies communities of practice or projects towards the bottom of the org chart where it fans out. Org charts also give some insight about tenure or level of competency based on vertical position.
Org charts are usually trees, from a single CEO through management to many workers. Since trees are graphs, it’s quite easy to import an org chart as a fundamental layer in a knowledge graph. In Figure 10-8 you see a visualization from Neo4j Bloom showing part of an organizational hierarchy. The CEO Alice sits at the top of the tree with her senior vice presidents (SVPs) underneath, connected via REPORTS_TO relationships. The SVPs are connected to their VPs via incoming REPORTS_TO relationships, and the same pattern extends to directors and ultimately individual contributors (ICs).
Figure 10-8. An organizational chart is a good basis for a skills knowledge graph
While Figure 10-8 doesn’t distinguish the levels of seniority of ICs (for example, senior analyst or principal consultant), it’s sufficient to enable you to reason about the intended structure of the organization. For example, you can easily run queries like that shown in Example 10-6 to understand how many employees are in a department or project, and from there be able to aggregate their costs.
Example 10-6. Finding people with Java project experience
MATCH (:VP {name:'Harry'})<-[:REPORTS_TO*1..2]-(n)RETURN count(n) AS numberOfEmployeesWhen you do, you get a result like that shown in Figure 10-9.
Knowledge graphs are a great fit for HR teams and managers looking to understand or change an organizational hierarchy. It’s easy to see how the knowledge graph in Figure 10-8 could be augmented to include a range of organizational and HR data for the employees.
But org charts are the intended structure of the organization, which is generally an approximation of its real structure, how it functions day to day. In most organizations there is an informal org chart which is rarely captured and even more rarely put into action. This is the org chart of how people actually work together, based on their skills and experience with delivering solutions.
Figure 10-9. Finding employees with Java skills
Skills Knowledge Graph
Section titled “Skills Knowledge Graph”At a basic level, finding skills in a knowledge graph is simple. For example, the query MATCH (ic:IC)-[:HAS_SKILL]->(s:Skill {name:'Java'}) RETURN ic.name will return the names of the ICs who have had Java programming experience, like in Figure 10-10.
But the results of that query are quite superficial. The results in Figure 10-10 say nothing about the level of proficiency, recency, or exposure of the individuals to real projects that use Java. Nor does it give any context for how those skills have been used over time. All you have is a name and a year when that person’s experience began. That’s probably not rich enough to make good staffing decisions, since you don’t even know when that skill was last exercised.
A better way to understand skills is to inspect an individual’s project experience, to aggregate the time spent honing particular skills and the time periods during which those skills were used. That connected context provides a richer view of an individual’s competencies than any checklist could.
Of course, with a knowledge graph it’s easy to add in those connections with minimal fuss. After some refactoring, a more effective knowledge graph emerges, as shown in Figure 10-11.
Figure 10-11. Programmers’ Java project experience
Figure 10-11 is a much more realistic example of the kind of enterprise knowledge graph of projects, people, and expertise. In this case, the knowledge graph serves two purposes: a detailed repository of who worked on what and a way of finding skills. In this subgraph, there is a program of work called future-hr, which has been broken down into several projects. The inaugural project is guns-brixton, which appears to have been a solo effort using Java, Neo4j, and Linux by engineer James. This is explicit in the graph structure where (James)-[:PARTICIPATED_IN]-(guns-brixton) and (guns-brixton)-[:REQUIRES]->(Neo4j). The inaugural project in the program must have been guns-brixton because it has no outgoing project dependencies, only an incoming DEPENDS relationship from the next project rock-casbah. The project dependency and staffing structure continues to the last project, career-opportunities, which has no dependencies and is therefore the last project in the program.
Now you can use projects and even programs to understand which people have been involved with various skills. The aggregate time with a particular skill across projects gives a reasonable approximation for skill level, and the recency of using that skill can be used to reason about how up to date a particular skill is.
As an example, using Figure 10-11 as a guide, you can create a query to find people who have been on projects involving Java. This is shown in Example 10-7, where the query transitively matches from people to skills via projects.
Example 10-7. Finding people with Java project experience
MATCH (java:Skill {name:'Java'})<-[:REQUIRES]-(:Project)<-[:PARTICIPATED_IN]-(ic:IC)RETURN DISTINCT ic.nameExample 10-7 is fine as a first approximation but lacks detail. A next useful step, shown in Example 10-8, is simply to count the number of Java projects that a person has participated in as a proxy for tenure.
Example 10-8. Finding people with Java project experience
MATCH (:Skill {name:'Java'})<-[:REQUIRES]-(:Project)<-[:PARTICIPATED]-(e:Employee)CALL { WITH e MATCH (e)-[:PARTICIPATED]->(p:Project) RETURN collect(duration.inMonths(p.start, p.end).months) AS duration}RETURN DISTINCT e.name, reduce(total=0, number IN duration | total + number) AS monthsOfExperienceThe query in Example 10-8 builds on Example 10-7, adding aggregation so that the matching programmers are ranked by the number of Java projects in which they have participated. The CALL idiom is used to compose an aggregating subquery that computes the duration of individual employees’ Java experience. When run in this case, it returns that James and Hugo appear to be experienced Java programmers, with George having a little less experience, as shown in Figure 10-12.
Figure 10-12. A program history
From here, it’s not hard to see how you could enrich this knowledge graph to fit other valuable production uses. It already serves to surface latent skills knowledge, but with the addition of the workers’ personal profiles, project evaluations, and so forth, you can create a knowledge graph system that can help staff the best people on the most challenging or critical projects.
Expertise Knowledge Graph
Section titled “Expertise Knowledge Graph”So far, you’ve seen how knowledge graphs can be populated with data from people and project data to discover skills explicitly associated with patterns of work. This mirrors a traditional way of organization, where people from various parts of the org chart work on projects and get increasing seniority through tenure. Such metrics are a valuable signal, but they are not the only valuable signal.
Particularly in larger organizations, staff don’t only orient themselves around the org chart or project team. There are often long-lived communities of interest in particular tools or skills. Finding the experts in these communities can help to provide a complementary signal to your org chart and project statistics; in fact, it might even be considered the real organizational chart for your business.
For information workers, at least, the modern enterprise can be remarkably flat. While they still have to adhere to some protocols and be somewhat mindful of the org chart hierarchy, peer collaboration is often strongly encouraged and facilitated by enterprise collaboration systems. Systems like Slack, Microsoft Teams, and so forth allow employees not only to communicate in a point-to-point fashion but also to form communities around long-lived topics. Within those communities are people with deep expertise and experience looking to help others and those who are seeking to participate to upgrade their skills or find help.
If the communities and their experts can be discovered, they can be amplified to the benefit of all concerned. However, platforms like Slack and Microsoft Teams don’t offer structured data beyond users, conversations, and threading. Finding good information or experts is difficult and often relies on word of mouth. As such, experience is varied, with a distinct bias against new employees who haven’t yet developed their work network.
Enriching your knowledge graph by adding a layer from the data in your collaboration platform can help. After all, wouldn’t it be nice if your skills record was automatically updated with expertise scores based on the quality of your interactions on Slack or Teams?
The kind of model that enterprise collaboration platforms have is very amenable to knowledge graphs. Moreover, some of the work that you might do with graph data science, such as community detection, is implicit in the channels that employees join. A knowledge graph representation of Slack’s core idioms is shown in Figure 10-13. It allows for patterns like (:User)-[:WROTE]->(:Message)-[:POSTED_TO]->(:Channel) and (:Message)-[:MENTIONS]->(:Skill), which transitively allow you to understand those users who are writing or responding to messages about a particular skill. It also contains the platform structural data around channels and topics to allow generalization from simply skills to channels containing a community of people who possess (or at least discuss) those skills.
Figure 10-13. A knowledge graph model for Slack collaboration
Figure 10-13 isn’t difficult to understand; it’s probably very similar to how you’d draw the domain on a whiteboard. But despite its simplicity, it does not lack capability. For any given skill, you can trivially determine who engages most across the organization, as shown in Example 10-9.
Example 10-9. Finding the most engaged people for Intermediate Language (IL) techniques
MATCH (m:Message)-[:POSTED_TO]->(c:Channel)-[:TOPIC]->(s:Skill {name:'IL'})<-[:MENTIONS]-(m)MATCH (m)<-[:REPLY*]-(r:Message)<-[:WROTE]-(u:User)WITH u AS user, count(r) AS replies, s AS skill,collect(DISTINCT c.name) AS channel ORDER BY replies DESCRETURN skill.name, user.name, replies, size(channel) AS numberOfChannelsBy now, the Cypher code in Example 10-9 should feel familiar. It first finds original postings on a particular Skill, which can appear in any channel. From there, it matches against a path of Message nodes joined by REPLY relationships to get conversation threads. Then the query aggregates the results. To do so, it uses the number of replies to order the results in a descending fashion. It collects the channels in which each thread appears into a list using DISTINCT to ensure no duplicates. Finally, it returns the skill, the users who have participated in threads about that skill along with how many times they have replied, and the number of channels across which they have replied. If you run the query, you get a result like that shown in Figure 10-14.
| skill.name | user.name | replies | numberOfChannels |
|---|---|---|---|
| “IL” | “James” | 7 | 2 |
| “IL” | “Hugo” | 2 | 1 |
| “IL” | “Jack” | 2 | 1 |
| “IL” | “George” | 1 | 1 |
| “IL” | “Rosa” | 1 | 1 |
Figure 10-14. Users who have significantly participated in discussions on a specific topic across one or more channels
It is not difficult to see how this generalizes so that you can identify experts in your organization. In a way, the expertise graph is the complement to your official organizational chart. As Andy Grove states in High Output Management, 2nd edition (Vintage Books), employees have organizational power because of the organizational chart or knowledge power because of their skills. Sometimes they have both, in the case of skilled managers. A knowledge graph is an excellent way of merging these two axes for a significantly richer understanding of your enterprise’s staffing.
Individual Career Growth
Section titled “Individual Career Growth”A knowledge graph like the one in Figure 10-13 is hugely useful for individuals. For any given topic, the system can easily recommend a likely expert who can advise to reduce project risk and time and transfer knowledge to help upskill others.
But there are other benefits of a skills knowledge graph for the individual. The foundational knowledge contained in such a system is the employee’s project history. As an individual, it becomes simple to look back at your project and skills history, which gives you a feel for your general career direction. This is shown in Example 10-10.
Example 10-10. Project history for individuals
MATCH (:Employee {name:'Rosa'})-[part:PARTICIPATED]->(p:Project)-[r:REQUIRES]->(s:Skill)WITH p AS proj, s AS skill, part.end AS lastUsed,duration.inDays(part.start, part.end).days AS daysRETURN skill.name AS skill, sum(days) AS daysOfExperience,max(lastUsed) ORDER BY daysOfExperience DESCThe MATCH clause in Example 10-10 finds a specific employee and the projects in which they have participated. From there, it finds the skills deployed on that project. It then calculates the duration in days that the employee spent on each project in the WITH clause. The RETURN clause aggregates that data into a short report. It returns the skill, how many days’ experience in total the employee has with that skill, and the last date when it was used (on the basis that recently used skills are fresher). The results are presented in descending order by days of experience in the skill. An example of the output from running the query in Example 10-10 is shown in Figure 10-15.
| skill | daysOfExperience | lastUsed |
|---|---|---|
| “Neo4j” | 1306 | “2022-10-03” |
| “Linux” | 1244 | “2022-10-03” |
| “Python” | 791 | “2021-07-06” |
| “JavaScript” | 789 | “2022-10-03” |
| “Java” | 515 | “2022-10-03” |
| “Windows” | 62 | “2020-12-12” |
Figure 10-15. Quantifying an individual’s project history and skills exposure
Clearly, the query in Example 10-10 provides useful results in itself, but it also forms the bedrock of more sophisticated analyses. One of the most compelling analyses for employees is to recommend skills for career paths. Career recommendations draw heavily on being able to reason about the individual’s project history and accumulated skills, but within the context of others whose skills and career progression can act as guides. This is a pattern that is readily exploitable, as shown in Example 10-11.
Example 10-11. Project history for individuals
MATCH (me:Employee {name:'Rosa'})-[:PARTICIPATED]->(:Project)<-[:PARTICIPATED]-(other:Employee)MATCH (other)-[:PARTICIPATED]->(:Project)-[:REQUIRES]->(s:Skill)WHERE NOT (me)-[:PARTICIPATED]->(:Project)-[:REQUIRES]->(s)WITH s AS skill, count(s) AS popularityRETURN DISTINCT skill.name, popularity ORDER BY popularity DESCThe key aspect of the Cypher query in Example 10-11 is to find people with whom you have a shared project history who have gone on to other projects where they have been exposed to new skills that you have not. Those skills to which you have not been exposed are probably good things to learn.
The first MATCH clause simply surfaces projects in which Rosa and other employees have participated. The second MATCH finds projects that others have worked on and the skills they have encountered during those projects. It is narrowed by the WHERE clause, which includes only those projects that Rosa hasn’t worked on. This leaves only the skills possessed by people Rosa has worked with but that Rosa herself does not have. Finally, the query ends by returning those skills ordered by their popularity in Rosa’s peer group.
You can see clearly in Figure 10-16 that the primary skill Rosa should consider learning is Java if she wants to mimic most of her project peers. This is followed by a list of other technologies her peer group has been exposed to, in descending order of popularity.
Figure 10-16. Recommendations for upskilling based on project history
The examples you’ve seen provide immediate value for solving important HR problems. But they also form the basis for more sophisticated analyses.
For example, it’s straightforward to add a simple taxonomy of skills so that staffing can be reasoned about at a generalized and specialized level. This means you can think about the general skill of databases versus the specific skill of NoSQL, or the general skill of functional programming versus the specific skill of F#.
Organizational Planning
Section titled “Organizational Planning”Recall the individual employee project history query from Example 10-10. As it happens, with minor tweaks this is precisely the kind of query that managers in an organization use when looking across the employee base for particular skills and experience. Whereas Example 10-10 curated the results around an individual employee by using their name property in the (:Employee) node, the manager’s query could analyze developer skills ranking across the network.
Example 10-14. Productive cliques
UNWIND ["Rosa", "Hugo", "Eve", "Petra", "Mark"] AS candidateMATCH (me:Employee {name:candidate})MATCH (me)-[r1:RATED]->(other:Employee)MATCH (me)<-[r2:RATED]-(other:Employee)WITH me AS myself, reduce(score = 0, r IN r1.ratings | score + r)/size(r1.ratings) + reduce(score = 0, r IN r2.ratings | score + r)/size(r2.ratings)/2 AS score, other AS them, r1, r2WHERE score >= 5RETURN myself, them, score, r1, r2The main change in Example 10-14 is that only high mutual ratings are returned using WHERE score >= 5, and the RATING relationships are also returned. This allows the graph to be rendered visually, as shown in Figure 10-20, which can be a much more intuitive view of the data.
Figure 10-20. A subgraph of mutually highly ranked employees
The scoring mathematics in this example is on the simple side, but for your organization, you can make that scoring as sophisticated as you need. Whatever scoring arithmetic you choose, the notion of using the social graph to fine-tune team composition is a solid foundation.
Predicting Organizational Performance
Section titled “Predicting Organizational Performance”The benefits of a skills knowledge graph rooted in the organization’s people and projects is clearly very useful. But knowledge graphs can go far beyond workforce development. They can also be used to evaluate and reason about the likely outcomes of future projects based on past outcomes. For example, Figure 10-21 shows the subgraph containing workers and their managers around two incomplete projects.
Figure 10-21. Incomplete projects in the organization
In Figure 10-21, the staffing on the projects is interesting. In fact, you can use it as the basis for reasoning—in broad terms—about the likely outcomes for the projects underway. For instance, poor managers or low-skilled workers could have a negative impact on the project, whereas a strong management structure and skilled workers might tend to have a positive effect. To get a sense of the history of failed projects and their chains of management, you can run a query like the one shown in Example 10-15.
Example 10-15. Looking for the leadership of failed projects
MATCH (p:Project)<-[:PARTICIPATED_IN]-(:IC)-[:REPORTS_TO*3..3]->(svp:SVP)WHERE p.rating < 30.0RETURN svp, count(p) AS failedProjects ORDER BY failedProjects DESCThe Cypher query in Example 10-15 binds to nodes with Project labels that satisfy the WHERE predicate that there is a property key rating (for completed projects only) and a value less than 30.0, which is considered a failed score. From there, it matches individual contributors who PARTICIPATED in the project and the leader three levels of management above them at SVP level via REPORTS_TO*3..3. It suggests that the project teams under SVP Lynn Smyth are much more often troubled than their contemporaries, as shown in Figure 10-22.
Figure 10-22. Failed projects that roll up to Lynn Smyth
Of course, at such a small scale the data can be made to tell almost any story. If you go deeper into Lynn’s history, there might be compelling reasons why project failure is more prominent. For example, she might run a research organization where even failed projects have value. Lynn is not the only SVP with some part of their portfolio having gone awry, but hers is somewhat more significant compared to the others.
Exhaustively pattern matching like this at a global scale is impractical and limiting. It would be much nicer if the knowledge graph could simply make good recommendations about project leaders that might be successful or give early warning about projects that might go astray. Graph data science gives you the tools to tackle this problem.
As you recall from Chapter 6, the first step is to create a projection from the knowledge graph that contains the nodes, relationships, and properties that you want to analyze. In this case, you want the entire knowledge graph structure of Employee, Project, and Incomplete nodes and PARTICIPATED_IN and REPORTS_TO relationships but only the rating property of Project nodes, as shown in Example 10-16. Ultimately, you want to be able to predict a rating property for projects that haven’t yet completed to predict likely outcomes.
Example 10-16. Creating a graph projection for historical and current projects
CALL gds.graph.project( 'projects', { Incomplete: {}, Project: { properties: ['rating'] }, Employee: {} }, { PARTICIPATED_IN: {orientation: 'UNDIRECTED'}, REPORTS_TO: {orientation: 'UNDIRECTED'} })The next step is to create an ML pipeline with CALL gds.alpha.pipeline.nodeRegression.create('projects-pipeline'). Now you can add a node regression procedure to the projects-pipeline, as shown in Example 10-17. In this case, the FastRP (https://oreil.ly/ljv0N) algorithm is chosen because it encodes knowledge graph topologies and data as numeric values suitable for ML. Here it encodes the topology of Project nodes as a numerical property on each of those nodes in the projection.
Example 10-17. Adding a node regression procedure into the ML pipeline
CALL gds.alpha.pipeline.nodeRegression.addNodeProperty( 'projects-pipeline', 'fastRP', { embeddingDimension: 256, iterationWeights: [0, 1], mutateProperty: 'fastrp-embedding', contextNodeLabels: ['Project'] })Next, you choose the features on which you’ll train the model. Since organizational topology is important in this case, the fastrp-embedding from Example 10-17 property is chosen, since FastRP encodes nodes’ topologies into a number suitable for use as a feature in ML. An example is shown in Example 10-18.
Example 10-18. Choosing features on which to train the model
CALL gds.alpha.pipeline.nodeRegression.selectFeatures( 'projects-pipeline', 'fastrp-embedding')The next step is to declare the split between training and testing data. In Example 10-19 testFraction is set to 0.2, meaning that 20% of the graph is reserved for testing the model (with the remainder being used for other purposes like training).
Example 10-19. Declare the ratio between training and testing data
CALL gds.alpha.pipeline.nodeRegression.configureSplit('projects-pipeline', { testFraction: 0.2})Next, you need to add a regression model to your pipeline. In this case, random forest is used. Random forest is a popular supervised ML method for classification and regression that consists of using several decision trees (to prevent overfitting on a single tree) and combining the trees’ individual predictions into an overall prediction. The configuration is shown in Example 10-20.
Example 10-20. Adding a regression model into the pipeline
CALL gds.alpha.pipeline.nodeRegression.addRandomForest('projects-pipeline', { numberOfDecisionTrees: 10})Now that the regression model and data are in place, the system is ready to tune. Since Neo4j Graph Data Science supports auto-tuning, it’s as simple as declaring the number of iterations the auto-ML system should execute before picking the best parameters. In this case, it’s computationally cheap enough to try 100 iterations, as shown in Example 10-21.
Example 10-21. Add configuration for regression parameter auto-tuning
CALL gds.alpha.pipeline.nodeRegression.configureAutoTuning('projects-pipeline', { maxTrials: 100})The penultimate step is to train a predictive model using all of the configuration specified previously. This is shown in Example 10-22. The model is trained on nodes with the Project label and the rating property in preparation for predicting the rating property of incomplete projects.
Example 10-22. Train the predictive model
CALL gds.alpha.pipeline.nodeRegression.train('projects', { pipeline: 'projects-pipeline', targetNodeLabels: ['Project'], modelName: 'projects-pipeline-model', targetProperty: 'rating', randomSeed: 1, concurrency: 4, metrics: ['MEAN_SQUARED_ERROR']})Finally, you have a trained model that can be used to make predictions about the health of incomplete projects. To use it, run the example code in Example 10-23, where the projects-pipeline-model is used to make predictions on nodes labeled Incomplete whose results are then streamed back to the user.
Example 10-23. Make predictions about project outcomes
CALL gds.alpha.pipeline.nodeRegression.predict.stream('projects', { modelName: 'projects-pipeline-model', targetNodeLabels: ['Incomplete']}) YIELD Node, predictedValueWITH gds.util.asNode(Node) AS projectNode, predictedValue AS predictedRatingRETURN projectNode.name AS name, predictedRatingORDER BY predictedRating ASC LIMIT 10The results from an execution of Example 10-23 are shown in Figure 10-23. In it, you can see the 10 projects with the poorest predicted scores. From here, you can continue to perform further data science on the knowledge graph to better understand why specific projects might fail, or you might take action at a business level to confirm the findings. Either way, at least you now have guidance on which projects could benefit from early intervention.
| name | predictedRating |
|---|---|
| ‘location-illegal’ | 27.534 |
| ‘act-event’ | 27.534 |
| ‘trouble-routine’ | 27.534 |
| ‘pipe-regular’ | 27.534 |
| ‘it-honey’ | 27.534 |
| ‘writing-orange’ | 27.534 |
Figure 10-23. Projects that might be prone to failure
This approach has two key benefits. For the organization looking to improve, it helps to track outcomes by department/leader and skill set and to predict future outcomes based on a notion of past competence held in the knowledge graph. It can help leaders in difficulty to improve or help to identify systemic barriers that lead to prolonged poor performance. This approach can also be a starting point for organizational redesign if the knowledge graph reveals persistent structural or individual failings.
For individuals looking to upskill, this approach can help navigate to areas where project delivery is mature, so teams have the breathing space to help new members learn. For those individuals looking to show their mettle, it can point to opportunities across their organization where the skill set matches but where the opportunities to join a strong team or strengthen a failing team are explicit. Whichever of the paths is taken, the individual employee is given significantly better visibility into what will be expected of them.
What is very clear at this point is that the skills knowledge graph takes you from a narrow world of “five years Java and Agile practices” to a world where individuals have a rich history of skills in context of delivery. An individual’s past and future career skills all enrich the knowledge graph, helping those individuals get the best from their careers as well as helping the organization to plan for the future.
Case Study: DXC Technology
DXC Technology is a global IT services company employing 130,000 people. To thrive in a competitive marketplace, DXC has to attract, retain, and upskill its team so that it can provide the utmost level of consultancy service and delivery expertise to clients.
DXC wanted to create a system where employees can easily get recommended career-development advice, based on the roles and career pathways that would be most valuable to the organization. The system should make it simple for employees to upskill and cross-skill based on available roles within the company.
However, like many other large enterprises, DXC has information silos and disconnected systems. While those systems are all valuable in their own right, they weren’t able to provide a connected view to employees. This led to challenges around hiring and promotions as well as in creating career pathways to support the growth of employees and the business. In times of high demand, employees were lost to attrition, and in times of workforce reductions, suboptimal decisions were made.
To remedy these problems, creating better opportunities for DXC employees and better outcomes for customers, DXC developed the Career Navigator. The DXC Career Navigator connects all the siloed data and generates intelligent recommendations, underpinned by an employee knowledge graph similar to the examples in this chapter.
Now all an employee’s interactions with the knowledge graph are mediated by an application that starts by making recommendations based on skill progressions of similar employees. For example, the tool recommends skills for a software engineer based on the gaps between their skill sets and those of similar software engineers.
DXC’s Career Navigator uses a combination of Neo4j’s graph database and Graph Data Science library. The knowledge graph hosted on Neo4j contains all the structural information about the employees and their skills. The graph algorithms executed by Graph Data Science enrich the knowledge graph by identifying similarly skilled employees, which can be used as a prototype for others’ career progression.
DXC’s Career Navigator has been so successful that the company is now offering it as a solution to its customers.
Pattern Detection with Embedded Rust Graphs
Section titled “Pattern Detection with Embedded Rust Graphs”When building high-performance, embedded systems in Rust using petgraph, you can achieve incredibly low-latency pattern detection without the overhead of network calls or query parsing. This is ideal for real-time systems, such as a fraud detection microservice sitting inline with a payment processor.
Because petgraph gives you direct access to the graph data structure in memory, finding a fraud ring is a matter of traversing the graph programmatically. Let’s look at how you might implement a fraud ring detection algorithm similar to Example 10-4, but natively in Rust.
Example 10-24. Detecting Fraud Rings in Rust using petgraph
use petgraph::graph::{Graph, NodeIndex};use petgraph::visit::Dfs;use std::collections::HashSet;
// Define our graph schema#[derive(Debug, Clone, PartialEq)]pub enum NodeData { Person { id: String }, Address { address: String }, Phone { number: String },}
#[derive(Debug, Clone)]pub enum EdgeData { LivesAt, Owns,}
/// A function to detect potential synthetic identity rings./// It looks for cycles or deep connections between Person nodes via shared Address/Phone nodes.pub fn detect_fraud_rings(graph: &Graph<NodeData, EdgeData>, start_node: NodeIndex) -> bool { // We only want to start the check if the node is a Person if let NodeData::Person { .. } = graph[start_node] { // We will use a Breadth-First Search (or DFS) to explore the local neighborhood let mut dfs = Dfs::new(graph, start_node); let mut visited_persons = HashSet::new(); let mut depth = 0;
while let Some(nx) = dfs.next(graph) { // Prevent runaway traversals in massive graphs by limiting depth depth += 1; if depth > 100 { break; }
if let NodeData::Person { id } = &graph[nx] { // If we encounter a person we've already seen, and it's not the start node, // we have found a cycle (a ring) if nx != start_node && visited_persons.contains(id) { return true; // Fraud ring detected! } visited_persons.insert(id.clone()); } } } false}In a production Rust system, you would wrap this petgraph instance behind a web framework like Axum (as shown in Chapter 5) or consume a Kafka stream directly. When a new transaction arrives, you look up the Person node associated with the credit card and run detect_fraud_rings(graph, person_node_idx). Because this happens entirely in memory with $O(1)$ pointer hops, the latency is measured in microseconds, allowing you to easily block fraudulent transactions in real time before they are approved.
Summary
Section titled “Summary”Uncovering and understanding patterns in your domain is a key competitive differentiator. Using pattern detection knowledge graphs is a powerful way of unlocking that skill.
The examples you have seen in this chapter provide a firm foundation upon which you can build your own pattern detection knowledge graphs. You can freely mix human expertise with insight from graph data science practices to enrich your knowledge graph. In turn, that enriched knowledge graph can be put into production to serve online and analytical use cases with equal competence.
But the techniques you’ve learned in this chapter have broader applicability. They are not only for social networks like fraudsters or business networks of colleagues and projects. In the following chapter, you’ll learn how to process patterns of dependencies within systems for such varied domains as supply chain and risk management.