SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
Decision Trees in Neo4j
Build dynamic expert systems and rules engines.
github.com/maxdemarzi
About 200 public repositories
Max De Marzi
Neo4j Field Engineer
About
Me !
01
02
03
04
maxdemarzi.com
@maxdemarzi
Let’s start with a Sign
Rule for Getting In
• Anyone over 21 years old gets in.
• On some nights, women 18 years or older get in.
• On some nights, men 18 years or older get in.
• The last two change dynamically.
Represent in a Graph
Rule Node
• expression (String):
• (age >= 18) && gender.equals(“female”)
• parameter_names(String):
• age, gender
• parameter_types(String):
• Int, String
There was a time…
BEFORE
When the Traversal API ruled supreme
https://maxdemarzi.com/2015/09/04/flight-search-with-the-neo4j-traversal-api/
Learn more… or read the docs
The Stored Procedure
@Procedure(name = "com.maxdemarzi.traverse.decision_tree", mode = Mode.READ)
@Description("CALL com.maxdemarzi.traverse.decision_tree(tree, facts)")
public Stream<PathResult> traverseDecisionTree(
@Name("tree") String id,
@Name("facts") Map<String, String> facts){
// Which Decision Tree are we interested in?
Node tree = db.findNode(Labels.Tree, "id", id);
if ( tree != null) {
// Find the paths by traversing this graph and the facts given
return decisionPath(tree, facts);
}
return null;
}
Tree Facts
private Stream<PathResult> decisionPath(Node tree, 

Map<String, String> facts) {
TraversalDescription myTraversal =
db.traversalDescription()
.depthFirst()
.expand(new DecisionTreeExpander(facts))
.evaluator(decisionTreeEvaluator);
return myTraversal
.traverse(tree)
.stream()
.map(PathResult::new);
}
Build a Traversal Description
public class DecisionTreeEvaluator implements PathEvaluator {
@Override
public Evaluation evaluate(Path path, BranchState branchState) {
// If we get to an Answer stop traversing, we found a valid path.
if (path.endNode().hasLabel(Labels.Answer)) {
return Evaluation.INCLUDE_AND_PRUNE;
} else {
// If not, continue down this path 

// to see if there is anything else to find.
return Evaluation.EXCLUDE_AND_CONTINUE;
}
}
Build a Path Evaluator
public class DecisionTreeExpander implements PathExpander {
private Map<String, String> facts;
private ExpressionEvaluator ee = new ExpressionEvaluator();
public DecisionTreeExpander(Map<String, String> facts) {
this.facts = facts;
ee.setExpressionType(boolean.class);
}
Build a Path Expander
@Override
public Iterable<Relationship> expand(Path path, BranchState branchState) {
// If we get to an Answer stop traversing, we found a valid path.
if (path.endNode().hasLabel(Labels.Answer)) {
return Collections.emptyList();
}
// If we have Rules to evaluate, go do that.
if (path.endNode()
.hasRelationship(Direction.OUTGOING, RelationshipTypes.HAS)) {
return path.endNode()
.getRelationships(Direction.OUTGOING, RelationshipTypes.HAS);
}
The expand method
if (path.endNode().hasLabel(Labels.Rule)) {
try {
if (isTrue(path.endNode())) {
return path.endNode()
.getRelationships(Direction.OUTGOING,
RelationshipTypes.IS_TRUE);
} else {
return path.endNode()
.getRelationships(Direction.OUTGOING,
RelationshipTypes.IS_FALSE);
}
} catch (Exception e) {
// Could not continue this way!
return Collections.emptyList();
}
}
The expand method (cont.)
boolean isTrue(Node rule) throws Exception {
Map<String, Object> ruleProperties = rule.getAllProperties();
String[] parameterNames =
Magic.explode((String) ruleProperties
.get("parameter_names"));
Class<?>[] parameterTypes =
Magic.stringToTypes((String) ruleProperties
.get("parameter_types"));
The isTrue method
Object[] arguments = new Object[parameterNames.length];
for (int j = 0; j < parameterNames.length; ++j) {
arguments[j] = Magic.createObject(parameterTypes[j],
facts.get(parameterNames[j]));
}
ee.setParameters(parameterNames, parameterTypes);
ee.cook((String)ruleProperties.get("expression"));
return (boolean) ee.evaluate(arguments);
The isTrue method (cont.)
Running it
CREATE (tree:Tree { id: 'bar entrance' })
CREATE (over21_rule:Rule { parameter_names: 'age',
parameter_types:'int',
expression:'age >= 21' })
CREATE (gender_rule:Rule { parameter_names: 'age,gender',
parameter_types:'int,String',
expression:'(age >= 18) && gender.equals("female")' })
CREATE (answer_yes:Answer { id: 'yes'})
CREATE (answer_no:Answer { id: 'no'})
CREATE (tree)-[:HAS]->(over21_rule)
CREATE (over21_rule)-[:IS_TRUE]->(answer_yes)
CREATE (over21_rule)-[:IS_FALSE]->(gender_rule)
CREATE (gender_rule)-[:IS_TRUE]->(answer_yes)
CREATE (gender_rule)-[:IS_FALSE]->(answer_no)
Build the Tree
CALL com.maxdemarzi.traverse.decision_tree(

‘bar entrance', {gender:'male', age:'20'})
YIELD path
RETURN path;
Check the Facts
Male, 20 years old?
It’s alright…
CALL com.maxdemarzi.traverse.decision_tree(

‘bar entrance', {gender:'female', age:’19'})
YIELD path
RETURN path;
Female, 19 years old?
Check the Facts
OMG…
Learn More…
https://maxdemarzi.com/2018/01/14/dynamic-rule-based-decision-trees-in-neo4j/
Details:
What about multiple Options?
https://maxdemarzi.com/2018/01/26/dynamic-rule-based-decision-trees-in-neo4j-part-2/
There is a Part 2
Decision Streams
• Paper: 

https://arxiv.org/pdf/1704.07657.pdf
• Authors:

Dmitry Ignatov and Andrey Ignatov
• Implementation: 

https://github.com/aiff22/Decision-Stream
Thank you!

Más contenido relacionado

La actualidad más candente

Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML SchemaRaji Ghawi
 
dotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsdotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsRob Napier
 
Java Hello World Program
Java Hello World ProgramJava Hello World Program
Java Hello World ProgramJavaWithUs
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)Gagan Agrawal
 

La actualidad más candente (6)

Java and XML Schema
Java and XML SchemaJava and XML Schema
Java and XML Schema
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
dotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsdotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World Protocols
 
Java Hello World Program
Java Hello World ProgramJava Hello World Program
Java Hello World Program
 
webScrapingFunctions
webScrapingFunctionswebScrapingFunctions
webScrapingFunctions
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
 

Similar a Build dynamic expert systems and rules engines with Decision Trees in Neo4j

MWLUG Session- AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
MWLUG Session-  AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...MWLUG Session-  AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
MWLUG Session- AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...Howard Greenberg
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConqeTimeline, LLC
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4)Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4)Binary Studio
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...DEEPANSHU GUPTA
 
Take a Trip Into the Forest: A Java Primer on Maps, Trees, and Collections
Take a Trip Into the Forest: A Java Primer on Maps, Trees, and Collections Take a Trip Into the Forest: A Java Primer on Maps, Trees, and Collections
Take a Trip Into the Forest: A Java Primer on Maps, Trees, and Collections Teamstudio
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013yohanbeschi
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Explain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).pptExplain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).pptayaankim007
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersHicham QAISSI
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with JerseyScott Leberknight
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012Timo Westkämper
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XMLguest2556de
 
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...Ruby Meditation
 

Similar a Build dynamic expert systems and rules engines with Decision Trees in Neo4j (20)

MWLUG Session- AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
MWLUG Session-  AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...MWLUG Session-  AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
MWLUG Session- AD112 - Take a Trip Into the Forest - A Java Primer on Maps, ...
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConq
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4)Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4)
Binary Studio Academy PRO: ANTLR course by Alexander Vasiltsov (lesson 4)
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
 
Take a Trip Into the Forest: A Java Primer on Maps, Trees, and Collections
Take a Trip Into the Forest: A Java Primer on Maps, Trees, and Collections Take a Trip Into the Forest: A Java Primer on Maps, Trees, and Collections
Take a Trip Into the Forest: A Java Primer on Maps, Trees, and Collections
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Explain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).pptExplain Classes and methods in java (ch04).ppt
Explain Classes and methods in java (ch04).ppt
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginners
 
RESTful Web Services with Jersey
RESTful Web Services with JerseyRESTful Web Services with Jersey
RESTful Web Services with Jersey
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
Simple API for XML
Simple API for XMLSimple API for XML
Simple API for XML
 
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
Dry-validation update. Dry-validation vs Dry-schema 1.0 - Aleksandra Stolyar ...
 
C++ 11 usage experience
C++ 11 usage experienceC++ 11 usage experience
C++ 11 usage experience
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Java 8 revealed
Java 8 revealedJava 8 revealed
Java 8 revealed
 

Más de Max De Marzi

DataDay 2023 Presentation
DataDay 2023 PresentationDataDay 2023 Presentation
DataDay 2023 PresentationMax De Marzi
 
DataDay 2023 Presentation - Notes
DataDay 2023 Presentation - NotesDataDay 2023 Presentation - Notes
DataDay 2023 Presentation - NotesMax De Marzi
 
Developer Intro Deck-PowerPoint - Download for Speaker Notes
Developer Intro Deck-PowerPoint - Download for Speaker NotesDeveloper Intro Deck-PowerPoint - Download for Speaker Notes
Developer Intro Deck-PowerPoint - Download for Speaker NotesMax De Marzi
 
Outrageous Ideas for Graph Databases
Outrageous Ideas for Graph DatabasesOutrageous Ideas for Graph Databases
Outrageous Ideas for Graph DatabasesMax De Marzi
 
Neo4j Training Cypher
Neo4j Training CypherNeo4j Training Cypher
Neo4j Training CypherMax De Marzi
 
Neo4j Training Modeling
Neo4j Training ModelingNeo4j Training Modeling
Neo4j Training ModelingMax De Marzi
 
Neo4j Training Introduction
Neo4j Training IntroductionNeo4j Training Introduction
Neo4j Training IntroductionMax De Marzi
 
Detenga el fraude complejo con Neo4j
Detenga el fraude complejo con Neo4jDetenga el fraude complejo con Neo4j
Detenga el fraude complejo con Neo4jMax De Marzi
 
Data Modeling Tricks for Neo4j
Data Modeling Tricks for Neo4jData Modeling Tricks for Neo4j
Data Modeling Tricks for Neo4jMax De Marzi
 
Fraud Detection and Neo4j
Fraud Detection and Neo4j Fraud Detection and Neo4j
Fraud Detection and Neo4j Max De Marzi
 
Detecion de Fraude con Neo4j
Detecion de Fraude con Neo4jDetecion de Fraude con Neo4j
Detecion de Fraude con Neo4jMax De Marzi
 
Neo4j Data Science Presentation
Neo4j Data Science PresentationNeo4j Data Science Presentation
Neo4j Data Science PresentationMax De Marzi
 
Neo4j Stored Procedure Training Part 2
Neo4j Stored Procedure Training Part 2Neo4j Stored Procedure Training Part 2
Neo4j Stored Procedure Training Part 2Max De Marzi
 
Neo4j Stored Procedure Training Part 1
Neo4j Stored Procedure Training Part 1Neo4j Stored Procedure Training Part 1
Neo4j Stored Procedure Training Part 1Max De Marzi
 
Neo4j y Fraude Spanish
Neo4j y Fraude SpanishNeo4j y Fraude Spanish
Neo4j y Fraude SpanishMax De Marzi
 
Data modeling with neo4j tutorial
Data modeling with neo4j tutorialData modeling with neo4j tutorial
Data modeling with neo4j tutorialMax De Marzi
 
Neo4j Fundamentals
Neo4j FundamentalsNeo4j Fundamentals
Neo4j FundamentalsMax De Marzi
 
Neo4j Presentation
Neo4j PresentationNeo4j Presentation
Neo4j PresentationMax De Marzi
 
Fraud Detection Class Slides
Fraud Detection Class SlidesFraud Detection Class Slides
Fraud Detection Class SlidesMax De Marzi
 

Más de Max De Marzi (20)

DataDay 2023 Presentation
DataDay 2023 PresentationDataDay 2023 Presentation
DataDay 2023 Presentation
 
DataDay 2023 Presentation - Notes
DataDay 2023 Presentation - NotesDataDay 2023 Presentation - Notes
DataDay 2023 Presentation - Notes
 
Developer Intro Deck-PowerPoint - Download for Speaker Notes
Developer Intro Deck-PowerPoint - Download for Speaker NotesDeveloper Intro Deck-PowerPoint - Download for Speaker Notes
Developer Intro Deck-PowerPoint - Download for Speaker Notes
 
Outrageous Ideas for Graph Databases
Outrageous Ideas for Graph DatabasesOutrageous Ideas for Graph Databases
Outrageous Ideas for Graph Databases
 
Neo4j Training Cypher
Neo4j Training CypherNeo4j Training Cypher
Neo4j Training Cypher
 
Neo4j Training Modeling
Neo4j Training ModelingNeo4j Training Modeling
Neo4j Training Modeling
 
Neo4j Training Introduction
Neo4j Training IntroductionNeo4j Training Introduction
Neo4j Training Introduction
 
Detenga el fraude complejo con Neo4j
Detenga el fraude complejo con Neo4jDetenga el fraude complejo con Neo4j
Detenga el fraude complejo con Neo4j
 
Data Modeling Tricks for Neo4j
Data Modeling Tricks for Neo4jData Modeling Tricks for Neo4j
Data Modeling Tricks for Neo4j
 
Fraud Detection and Neo4j
Fraud Detection and Neo4j Fraud Detection and Neo4j
Fraud Detection and Neo4j
 
Detecion de Fraude con Neo4j
Detecion de Fraude con Neo4jDetecion de Fraude con Neo4j
Detecion de Fraude con Neo4j
 
Neo4j Data Science Presentation
Neo4j Data Science PresentationNeo4j Data Science Presentation
Neo4j Data Science Presentation
 
Neo4j Stored Procedure Training Part 2
Neo4j Stored Procedure Training Part 2Neo4j Stored Procedure Training Part 2
Neo4j Stored Procedure Training Part 2
 
Neo4j Stored Procedure Training Part 1
Neo4j Stored Procedure Training Part 1Neo4j Stored Procedure Training Part 1
Neo4j Stored Procedure Training Part 1
 
Neo4j y Fraude Spanish
Neo4j y Fraude SpanishNeo4j y Fraude Spanish
Neo4j y Fraude Spanish
 
Data modeling with neo4j tutorial
Data modeling with neo4j tutorialData modeling with neo4j tutorial
Data modeling with neo4j tutorial
 
Neo4j Fundamentals
Neo4j FundamentalsNeo4j Fundamentals
Neo4j Fundamentals
 
Neo4j Presentation
Neo4j PresentationNeo4j Presentation
Neo4j Presentation
 
Fraud Detection Class Slides
Fraud Detection Class SlidesFraud Detection Class Slides
Fraud Detection Class Slides
 
Neo4j in Depth
Neo4j in DepthNeo4j in Depth
Neo4j in Depth
 

Último

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Último (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

Build dynamic expert systems and rules engines with Decision Trees in Neo4j

  • 1. Decision Trees in Neo4j Build dynamic expert systems and rules engines.
  • 2. github.com/maxdemarzi About 200 public repositories Max De Marzi Neo4j Field Engineer About Me ! 01 02 03 04 maxdemarzi.com @maxdemarzi
  • 4.
  • 5.
  • 6. Rule for Getting In • Anyone over 21 years old gets in. • On some nights, women 18 years or older get in. • On some nights, men 18 years or older get in. • The last two change dynamically.
  • 8.
  • 9. Rule Node • expression (String): • (age >= 18) && gender.equals(“female”) • parameter_names(String): • age, gender • parameter_types(String): • Int, String
  • 10. There was a time… BEFORE
  • 11.
  • 12. When the Traversal API ruled supreme
  • 15. @Procedure(name = "com.maxdemarzi.traverse.decision_tree", mode = Mode.READ) @Description("CALL com.maxdemarzi.traverse.decision_tree(tree, facts)") public Stream<PathResult> traverseDecisionTree( @Name("tree") String id, @Name("facts") Map<String, String> facts){ // Which Decision Tree are we interested in? Node tree = db.findNode(Labels.Tree, "id", id); if ( tree != null) { // Find the paths by traversing this graph and the facts given return decisionPath(tree, facts); } return null; } Tree Facts
  • 16. private Stream<PathResult> decisionPath(Node tree, 
 Map<String, String> facts) { TraversalDescription myTraversal = db.traversalDescription() .depthFirst() .expand(new DecisionTreeExpander(facts)) .evaluator(decisionTreeEvaluator); return myTraversal .traverse(tree) .stream() .map(PathResult::new); } Build a Traversal Description
  • 17.
  • 18. public class DecisionTreeEvaluator implements PathEvaluator { @Override public Evaluation evaluate(Path path, BranchState branchState) { // If we get to an Answer stop traversing, we found a valid path. if (path.endNode().hasLabel(Labels.Answer)) { return Evaluation.INCLUDE_AND_PRUNE; } else { // If not, continue down this path 
 // to see if there is anything else to find. return Evaluation.EXCLUDE_AND_CONTINUE; } } Build a Path Evaluator
  • 19.
  • 20. public class DecisionTreeExpander implements PathExpander { private Map<String, String> facts; private ExpressionEvaluator ee = new ExpressionEvaluator(); public DecisionTreeExpander(Map<String, String> facts) { this.facts = facts; ee.setExpressionType(boolean.class); } Build a Path Expander
  • 21. @Override public Iterable<Relationship> expand(Path path, BranchState branchState) { // If we get to an Answer stop traversing, we found a valid path. if (path.endNode().hasLabel(Labels.Answer)) { return Collections.emptyList(); } // If we have Rules to evaluate, go do that. if (path.endNode() .hasRelationship(Direction.OUTGOING, RelationshipTypes.HAS)) { return path.endNode() .getRelationships(Direction.OUTGOING, RelationshipTypes.HAS); } The expand method
  • 22. if (path.endNode().hasLabel(Labels.Rule)) { try { if (isTrue(path.endNode())) { return path.endNode() .getRelationships(Direction.OUTGOING, RelationshipTypes.IS_TRUE); } else { return path.endNode() .getRelationships(Direction.OUTGOING, RelationshipTypes.IS_FALSE); } } catch (Exception e) { // Could not continue this way! return Collections.emptyList(); } } The expand method (cont.)
  • 23.
  • 24. boolean isTrue(Node rule) throws Exception { Map<String, Object> ruleProperties = rule.getAllProperties(); String[] parameterNames = Magic.explode((String) ruleProperties .get("parameter_names")); Class<?>[] parameterTypes = Magic.stringToTypes((String) ruleProperties .get("parameter_types")); The isTrue method
  • 25. Object[] arguments = new Object[parameterNames.length]; for (int j = 0; j < parameterNames.length; ++j) { arguments[j] = Magic.createObject(parameterTypes[j], facts.get(parameterNames[j])); } ee.setParameters(parameterNames, parameterTypes); ee.cook((String)ruleProperties.get("expression")); return (boolean) ee.evaluate(arguments); The isTrue method (cont.)
  • 27.
  • 28.
  • 29. CREATE (tree:Tree { id: 'bar entrance' }) CREATE (over21_rule:Rule { parameter_names: 'age', parameter_types:'int', expression:'age >= 21' }) CREATE (gender_rule:Rule { parameter_names: 'age,gender', parameter_types:'int,String', expression:'(age >= 18) && gender.equals("female")' }) CREATE (answer_yes:Answer { id: 'yes'}) CREATE (answer_no:Answer { id: 'no'}) CREATE (tree)-[:HAS]->(over21_rule) CREATE (over21_rule)-[:IS_TRUE]->(answer_yes) CREATE (over21_rule)-[:IS_FALSE]->(gender_rule) CREATE (gender_rule)-[:IS_TRUE]->(answer_yes) CREATE (gender_rule)-[:IS_FALSE]->(answer_no) Build the Tree
  • 30.
  • 31. CALL com.maxdemarzi.traverse.decision_tree(
 ‘bar entrance', {gender:'male', age:'20'}) YIELD path RETURN path; Check the Facts Male, 20 years old?
  • 32.
  • 34. CALL com.maxdemarzi.traverse.decision_tree(
 ‘bar entrance', {gender:'female', age:’19'}) YIELD path RETURN path; Female, 19 years old? Check the Facts
  • 35.
  • 37.
  • 42.
  • 43. Decision Streams • Paper: 
 https://arxiv.org/pdf/1704.07657.pdf • Authors:
 Dmitry Ignatov and Andrey Ignatov • Implementation: 
 https://github.com/aiff22/Decision-Stream
  • 44.