DPG 0.3.3__tar.gz → 0.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dpg-0.3.5/PKG-INFO ADDED
@@ -0,0 +1,190 @@
1
+ Metadata-Version: 2.4
2
+ Name: dpg
3
+ Version: 0.3.5
4
+ Summary: A Python library for extracting Decision Predicate Graphs and global explanations from ensemble models.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: decision graph,ensemble learning,explainable ai,explainability,global explanations
8
+ Author: Sylvio Barbon Junior
9
+ Author-email: sylvio.barbonjunior@units.it
10
+ Requires-Python: >=3.10
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Provides-Extra: dev
19
+ Provides-Extra: docs
20
+ Requires-Dist: contourpy (>=1.2)
21
+ Requires-Dist: cycler (>=0.12)
22
+ Requires-Dist: fonttools (>=4.53)
23
+ Requires-Dist: graphviz (>=0.20)
24
+ Requires-Dist: joblib (>=1.4)
25
+ Requires-Dist: kiwisolver (>=1.4)
26
+ Requires-Dist: matplotlib (>=3.9.1)
27
+ Requires-Dist: myst-nb (>=1.1) ; extra == "docs"
28
+ Requires-Dist: myst-parser (>=3.0) ; extra == "docs"
29
+ Requires-Dist: networkx (>=3.3)
30
+ Requires-Dist: numpy (>=2.0.0)
31
+ Requires-Dist: packaging (>=24.1)
32
+ Requires-Dist: pandas (>=2.2)
33
+ Requires-Dist: pillow (>=10.4)
34
+ Requires-Dist: pydata-sphinx-theme (>=0.15) ; extra == "docs"
35
+ Requires-Dist: pyparsing (>=3.1)
36
+ Requires-Dist: python-dateutil (>=2.9)
37
+ Requires-Dist: pytz (>=2024.1)
38
+ Requires-Dist: pyyaml (>=6.0.2)
39
+ Requires-Dist: scikit-learn (>=1.5)
40
+ Requires-Dist: scipy (>=1.14)
41
+ Requires-Dist: six (>=1.16)
42
+ Requires-Dist: sphinx (>=7.3) ; extra == "docs"
43
+ Requires-Dist: sphinx-autoapi (>=3.1) ; extra == "docs"
44
+ Requires-Dist: sphinx-copybutton (>=0.5) ; extra == "docs"
45
+ Requires-Dist: sphinx-design (>=0.6) ; extra == "docs"
46
+ Requires-Dist: threadpoolctl (>=3.5)
47
+ Requires-Dist: tqdm (>=4.67)
48
+ Requires-Dist: tzdata (>=2024.1)
49
+ Project-URL: Homepage, https://github.com/Meta-Group/DPG
50
+ Project-URL: Repository, https://github.com/Meta-Group/DPG
51
+ Description-Content-Type: text/markdown
52
+
53
+ # Decision Predicate Graph (DPG)
54
+
55
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
56
+ [![Install with pip](https://img.shields.io/badge/pip%20install-dpg-3775A9?logo=pypi&logoColor=white)](https://pypi.org/project/dpg/)
57
+ [![Python Versions](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12-blue.svg)](pyproject.toml)
58
+ [![Tests](https://github.com/Meta-Group/DPG/actions/workflows/tests.yml/badge.svg)](https://github.com/Meta-Group/DPG/actions/workflows/tests.yml)
59
+ [![Release](https://github.com/Meta-Group/DPG/actions/workflows/release.yml/badge.svg)](https://github.com/Meta-Group/DPG/actions/workflows/release.yml)
60
+ [![Documentation Status](https://app.readthedocs.org/projects/dpg/badge/?version=latest)](https://dpg.readthedocs.io/en/latest/)
61
+ [![Try the DPG sandbox](https://img.shields.io/badge/DPG%20sandbox-Try%20it%20in%20browser-4B5E27?logo=googlechrome&logoColor=white)](https://machinelearning.inginf.units.it/DPG_web/#how)
62
+
63
+ <p align="center">
64
+ <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/DPG.png" alt="DPG logo" width="300">
65
+ </p>
66
+
67
+ DPG is a model-agnostic framework for explaining tree ensembles. It converts
68
+ their decision logic into a graph, making predicates, transitions, predictions,
69
+ and structural diagnostics available in one representation.
70
+
71
+ ## Highlights
72
+
73
+ - Global and local explanations through `DPGExplainer`
74
+ - Graph metrics, including constraints, betweenness centrality, local reaching
75
+ centrality, and communities
76
+ - Local-path inspection, local-on-global plots, and faithfulness diagnostics
77
+ - Support for common scikit-learn tree ensembles
78
+
79
+ ## Install
80
+
81
+ ```bash
82
+ pip install dpg
83
+ ```
84
+
85
+ DPG requires Python 3.10 or later. To render graphs, also install the Graphviz
86
+ system package so that `dot` is on your `PATH`.
87
+
88
+ For development and documentation builds, see [docs/README.md](docs/README.md).
89
+
90
+ ## Quick start
91
+
92
+ ```python
93
+ import numpy as np
94
+ from sklearn.datasets import load_iris
95
+ from sklearn.ensemble import RandomForestClassifier
96
+ from dpg import DPGExplainer
97
+
98
+ X, y = load_iris(return_X_y=True, as_frame=True)
99
+ model = RandomForestClassifier(n_estimators=5, random_state=42).fit(X, y)
100
+
101
+ explainer = DPGExplainer(
102
+ model=model,
103
+ feature_names=X.columns.tolist(),
104
+ target_names=np.unique(y).astype(str).tolist(),
105
+ )
106
+ explanation = explainer.explain_global(X.values, communities=True)
107
+ explainer.plot("iris_dpg", explanation, save_dir="results")
108
+ ```
109
+
110
+ ## How DPG works
111
+
112
+ The concept behind DPG is to convert a generic tree-based ensemble model for classification into a graph, where:
113
+ - Nodes represent predicates, i.e., the feature-value associations present in each node of every tree;
114
+ - Edges denote the frequency with which these predicates are satisfied during the model training phase by the samples of the dataset.
115
+
116
+ <p align="center">
117
+ <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example.png" width="600" />
118
+ </p>
119
+
120
+ ## Metrics
121
+
122
+ The graph-based nature of DPG provides significant enhancements in the direction of a complete mapping of the ensemble structure.
123
+
124
+ | Property | Definition | Utility |
125
+ |--------------|------------|---------|
126
+ | _Constraints_ | The intervals of values for each feature obtained from all predicates connected by a path that culminates in a given class. | Calculate the classification boundary values of each feature associated with each class. |
127
+ | _Betweenness centrality_ | Quantifies the fraction of all the shortest paths between every pair of nodes of the graph passing through the considered node. | Identify potential bottleneck nodes that correspond to crucial decisions. |
128
+ | _Local reaching centrality_ | Quantifies the proportion of other nodes reachable from the local node through its outgoing edges. | Assess the importance of nodes similarly to feature importance, but enrich the information by encompassing the values associated with features across all decisions. |
129
+ | _Community_ | A subset of nodes of the DPG which is characterised by dense interconnections between its elements and sparse connections with the other nodes of the DPG that do not belong to the community. | Understanding the characteristics of nodes to be assigned to a particular community class, identifying predominant predicates, and those that play a marginal role in the classification process. |
130
+
131
+ |Constraints | Betweenness centrality | Local reaching centrality | Community|
132
+ |------------|------------|--------------|--------------------|
133
+ | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_constraints.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_bc.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_lrc.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_community.png) |
134
+ | Constraints(Class 1) = val3 < F1 ≤ val1, F2 ≤ val2 | BC(F2 ≤ val2) = 4/24 | LRC(F1 ≤ val1) = 6 / 7 | Community(Class 1) = F1 ≤ val1, F2 ≤ val2 |
135
+
136
+ ## Local explanations and faithfulness
137
+
138
+ Fit the explainer once, then inspect an individual prediction or compare local
139
+ explanations with the fitted model:
140
+
141
+ ```python
142
+ explainer.fit(X.values)
143
+ local = explainer.explain_local(X.iloc[0].values, sample_id=0)
144
+ details = explainer.evaluate_faithfulness(X.values, return_details=True)
145
+
146
+ print(local.majority_vote)
147
+ print(details["faithfulness_score"])
148
+ ```
149
+
150
+ `evaluate_faithfulness` reports model agreement, trace coverage,
151
+ recombination, evidence margin, and a composite heuristic score. It is an
152
+ explanation-fidelity measure, not a probability of ground-truth correctness.
153
+
154
+ ## Documentation and examples
155
+
156
+ - [Full documentation](https://dpg.readthedocs.io/en/latest/)
157
+ - [Quickstart](https://dpg.readthedocs.io/en/latest/quickstart.html)
158
+ - [Supported models](https://dpg.readthedocs.io/en/latest/supported_models.html)
159
+ - [Visualizations](https://dpg.readthedocs.io/en/latest/visualization.html)
160
+ - [Examples](examples), including [local explanations](examples/local_explanation_iris.py)
161
+ - [Parameter-sensitivity benchmark](tutorials/parameter_sensitivity_benchmark/README.md)
162
+ - [Interactive DPG sandbox](https://machinelearning.inginf.units.it/DPG_web/#how) — explore how DPG turns an ensemble into a graph in the browser.
163
+
164
+ <p align="center">
165
+ <a href="https://machinelearning.inginf.units.it/DPG_web/#how">
166
+ <img src="docs/_static/DPG.png" alt="Open the interactive DPG sandbox" width="180">
167
+ </a>
168
+ </p>
169
+
170
+ The packaged CLI mirrors `examples/run_dpg_standard.py`. Run `dpg --help` for
171
+ its current options and use `examples/run_dpg_custom.py` for a dataset with a
172
+ specified target column.
173
+
174
+ ## Citation
175
+
176
+ If you use DPG in research, please cite:
177
+
178
+ ```bibtex
179
+ @inproceedings{arrighi2024dpg,
180
+ title={Decision Predicate Graphs: Enhancing Interpretability in Tree Ensembles},
181
+ author={Arrighi, Leonardo and Pennella, Luca and Marques Tavares, Gabriel and Barbon Junior, Sylvio},
182
+ booktitle={World Conference on Explainable Artificial Intelligence},
183
+ pages={311--332},
184
+ year={2024},
185
+ isbn={978-3-031-63797-1},
186
+ doi={10.1007/978-3-031-63797-1_16},
187
+ publisher={Springer Nature Switzerland},
188
+ }
189
+ ```
190
+
dpg-0.3.5/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # Decision Predicate Graph (DPG)
2
+
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
4
+ [![Install with pip](https://img.shields.io/badge/pip%20install-dpg-3775A9?logo=pypi&logoColor=white)](https://pypi.org/project/dpg/)
5
+ [![Python Versions](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12-blue.svg)](pyproject.toml)
6
+ [![Tests](https://github.com/Meta-Group/DPG/actions/workflows/tests.yml/badge.svg)](https://github.com/Meta-Group/DPG/actions/workflows/tests.yml)
7
+ [![Release](https://github.com/Meta-Group/DPG/actions/workflows/release.yml/badge.svg)](https://github.com/Meta-Group/DPG/actions/workflows/release.yml)
8
+ [![Documentation Status](https://app.readthedocs.org/projects/dpg/badge/?version=latest)](https://dpg.readthedocs.io/en/latest/)
9
+ [![Try the DPG sandbox](https://img.shields.io/badge/DPG%20sandbox-Try%20it%20in%20browser-4B5E27?logo=googlechrome&logoColor=white)](https://machinelearning.inginf.units.it/DPG_web/#how)
10
+
11
+ <p align="center">
12
+ <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/DPG.png" alt="DPG logo" width="300">
13
+ </p>
14
+
15
+ DPG is a model-agnostic framework for explaining tree ensembles. It converts
16
+ their decision logic into a graph, making predicates, transitions, predictions,
17
+ and structural diagnostics available in one representation.
18
+
19
+ ## Highlights
20
+
21
+ - Global and local explanations through `DPGExplainer`
22
+ - Graph metrics, including constraints, betweenness centrality, local reaching
23
+ centrality, and communities
24
+ - Local-path inspection, local-on-global plots, and faithfulness diagnostics
25
+ - Support for common scikit-learn tree ensembles
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install dpg
31
+ ```
32
+
33
+ DPG requires Python 3.10 or later. To render graphs, also install the Graphviz
34
+ system package so that `dot` is on your `PATH`.
35
+
36
+ For development and documentation builds, see [docs/README.md](docs/README.md).
37
+
38
+ ## Quick start
39
+
40
+ ```python
41
+ import numpy as np
42
+ from sklearn.datasets import load_iris
43
+ from sklearn.ensemble import RandomForestClassifier
44
+ from dpg import DPGExplainer
45
+
46
+ X, y = load_iris(return_X_y=True, as_frame=True)
47
+ model = RandomForestClassifier(n_estimators=5, random_state=42).fit(X, y)
48
+
49
+ explainer = DPGExplainer(
50
+ model=model,
51
+ feature_names=X.columns.tolist(),
52
+ target_names=np.unique(y).astype(str).tolist(),
53
+ )
54
+ explanation = explainer.explain_global(X.values, communities=True)
55
+ explainer.plot("iris_dpg", explanation, save_dir="results")
56
+ ```
57
+
58
+ ## How DPG works
59
+
60
+ The concept behind DPG is to convert a generic tree-based ensemble model for classification into a graph, where:
61
+ - Nodes represent predicates, i.e., the feature-value associations present in each node of every tree;
62
+ - Edges denote the frequency with which these predicates are satisfied during the model training phase by the samples of the dataset.
63
+
64
+ <p align="center">
65
+ <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example.png" width="600" />
66
+ </p>
67
+
68
+ ## Metrics
69
+
70
+ The graph-based nature of DPG provides significant enhancements in the direction of a complete mapping of the ensemble structure.
71
+
72
+ | Property | Definition | Utility |
73
+ |--------------|------------|---------|
74
+ | _Constraints_ | The intervals of values for each feature obtained from all predicates connected by a path that culminates in a given class. | Calculate the classification boundary values of each feature associated with each class. |
75
+ | _Betweenness centrality_ | Quantifies the fraction of all the shortest paths between every pair of nodes of the graph passing through the considered node. | Identify potential bottleneck nodes that correspond to crucial decisions. |
76
+ | _Local reaching centrality_ | Quantifies the proportion of other nodes reachable from the local node through its outgoing edges. | Assess the importance of nodes similarly to feature importance, but enrich the information by encompassing the values associated with features across all decisions. |
77
+ | _Community_ | A subset of nodes of the DPG which is characterised by dense interconnections between its elements and sparse connections with the other nodes of the DPG that do not belong to the community. | Understanding the characteristics of nodes to be assigned to a particular community class, identifying predominant predicates, and those that play a marginal role in the classification process. |
78
+
79
+ |Constraints | Betweenness centrality | Local reaching centrality | Community|
80
+ |------------|------------|--------------|--------------------|
81
+ | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_constraints.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_bc.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_lrc.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_community.png) |
82
+ | Constraints(Class 1) = val3 < F1 ≤ val1, F2 ≤ val2 | BC(F2 ≤ val2) = 4/24 | LRC(F1 ≤ val1) = 6 / 7 | Community(Class 1) = F1 ≤ val1, F2 ≤ val2 |
83
+
84
+ ## Local explanations and faithfulness
85
+
86
+ Fit the explainer once, then inspect an individual prediction or compare local
87
+ explanations with the fitted model:
88
+
89
+ ```python
90
+ explainer.fit(X.values)
91
+ local = explainer.explain_local(X.iloc[0].values, sample_id=0)
92
+ details = explainer.evaluate_faithfulness(X.values, return_details=True)
93
+
94
+ print(local.majority_vote)
95
+ print(details["faithfulness_score"])
96
+ ```
97
+
98
+ `evaluate_faithfulness` reports model agreement, trace coverage,
99
+ recombination, evidence margin, and a composite heuristic score. It is an
100
+ explanation-fidelity measure, not a probability of ground-truth correctness.
101
+
102
+ ## Documentation and examples
103
+
104
+ - [Full documentation](https://dpg.readthedocs.io/en/latest/)
105
+ - [Quickstart](https://dpg.readthedocs.io/en/latest/quickstart.html)
106
+ - [Supported models](https://dpg.readthedocs.io/en/latest/supported_models.html)
107
+ - [Visualizations](https://dpg.readthedocs.io/en/latest/visualization.html)
108
+ - [Examples](examples), including [local explanations](examples/local_explanation_iris.py)
109
+ - [Parameter-sensitivity benchmark](tutorials/parameter_sensitivity_benchmark/README.md)
110
+ - [Interactive DPG sandbox](https://machinelearning.inginf.units.it/DPG_web/#how) — explore how DPG turns an ensemble into a graph in the browser.
111
+
112
+ <p align="center">
113
+ <a href="https://machinelearning.inginf.units.it/DPG_web/#how">
114
+ <img src="docs/_static/DPG.png" alt="Open the interactive DPG sandbox" width="180">
115
+ </a>
116
+ </p>
117
+
118
+ The packaged CLI mirrors `examples/run_dpg_standard.py`. Run `dpg --help` for
119
+ its current options and use `examples/run_dpg_custom.py` for a dataset with a
120
+ specified target column.
121
+
122
+ ## Citation
123
+
124
+ If you use DPG in research, please cite:
125
+
126
+ ```bibtex
127
+ @inproceedings{arrighi2024dpg,
128
+ title={Decision Predicate Graphs: Enhancing Interpretability in Tree Ensembles},
129
+ author={Arrighi, Leonardo and Pennella, Luca and Marques Tavares, Gabriel and Barbon Junior, Sylvio},
130
+ booktitle={World Conference on Explainable Artificial Intelligence},
131
+ pages={311--332},
132
+ year={2024},
133
+ isbn={978-3-031-63797-1},
134
+ doi={10.1007/978-3-031-63797-1_16},
135
+ publisher={Springer Nature Switzerland},
136
+ }
137
+ ```
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "dpg"
3
- version = "0.3.3"
3
+ version = "0.3.5"
4
4
  description = "A Python library for extracting Decision Predicate Graphs and global explanations from ensemble models."
5
5
  authors = ["Sylvio Barbon Junior <sylvio.barbonjunior@units.it>", "Leonardo Arrighi <leonardo.arrighi@phd.units.it>"]
6
6
  license = "MIT"
dpg-0.3.3/PKG-INFO DELETED
@@ -1,432 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: dpg
3
- Version: 0.3.3
4
- Summary: A Python library for extracting Decision Predicate Graphs and global explanations from ensemble models.
5
- License: MIT
6
- License-File: LICENSE
7
- Keywords: decision graph,ensemble learning,explainable ai,explainability,global explanations
8
- Author: Sylvio Barbon Junior
9
- Author-email: sylvio.barbonjunior@units.it
10
- Requires-Python: >=3.10
11
- Classifier: License :: OSI Approved :: MIT License
12
- Classifier: Programming Language :: Python :: 3
13
- Classifier: Programming Language :: Python :: 3.10
14
- Classifier: Programming Language :: Python :: 3.11
15
- Classifier: Programming Language :: Python :: 3.12
16
- Classifier: Programming Language :: Python :: 3.13
17
- Classifier: Programming Language :: Python :: 3.14
18
- Provides-Extra: dev
19
- Provides-Extra: docs
20
- Requires-Dist: contourpy (>=1.2)
21
- Requires-Dist: cycler (>=0.12)
22
- Requires-Dist: fonttools (>=4.53)
23
- Requires-Dist: graphviz (>=0.20)
24
- Requires-Dist: joblib (>=1.4)
25
- Requires-Dist: kiwisolver (>=1.4)
26
- Requires-Dist: matplotlib (>=3.9.1)
27
- Requires-Dist: myst-nb (>=1.1) ; extra == "docs"
28
- Requires-Dist: myst-parser (>=3.0) ; extra == "docs"
29
- Requires-Dist: networkx (>=3.3)
30
- Requires-Dist: numpy (>=2.0.0)
31
- Requires-Dist: packaging (>=24.1)
32
- Requires-Dist: pandas (>=2.2)
33
- Requires-Dist: pillow (>=10.4)
34
- Requires-Dist: pydata-sphinx-theme (>=0.15) ; extra == "docs"
35
- Requires-Dist: pyparsing (>=3.1)
36
- Requires-Dist: python-dateutil (>=2.9)
37
- Requires-Dist: pytz (>=2024.1)
38
- Requires-Dist: pyyaml (>=6.0.2)
39
- Requires-Dist: scikit-learn (>=1.5)
40
- Requires-Dist: scipy (>=1.14)
41
- Requires-Dist: six (>=1.16)
42
- Requires-Dist: sphinx (>=7.3) ; extra == "docs"
43
- Requires-Dist: sphinx-autoapi (>=3.1) ; extra == "docs"
44
- Requires-Dist: sphinx-copybutton (>=0.5) ; extra == "docs"
45
- Requires-Dist: sphinx-design (>=0.6) ; extra == "docs"
46
- Requires-Dist: threadpoolctl (>=3.5)
47
- Requires-Dist: tqdm (>=4.67)
48
- Requires-Dist: tzdata (>=2024.1)
49
- Project-URL: Homepage, https://github.com/Meta-Group/DPG
50
- Project-URL: Repository, https://github.com/Meta-Group/DPG
51
- Description-Content-Type: text/markdown
52
-
53
- # Decision Predicate Graph (DPG)
54
-
55
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
56
- [![Python Versions](https://img.shields.io/badge/python-3.10%20|%203.11%20|%203.12-blue.svg)](pyproject.toml)
57
- [![Build Status](https://github.com/Meta-Group/DPG/actions/workflows/tests.yml/badge.svg)](https://github.com/Meta-Group/DPG/actions/workflows/tests.yml)
58
- [![Documentation Status](https://readthedocs.org/projects/dpg/badge/?version=latest)](https://dpg.readthedocs.io/en/latest/)
59
-
60
- <p align="center">
61
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/DPG.png" alt="DPG logo" width="300">
62
- </p>
63
-
64
-
65
- DPG is a model-agnostic framework for global and local explanation of tree-based ensemble models.
66
- It turns ensemble decision logic into a graph so users can inspect predicates, transitions, predictions,
67
- and structural explanation diagnostics in a single representation.
68
-
69
- DPG is a graph structure that captures the tree-based ensemble model and learned dataset details,
70
- preserving the relations among features, logical decisions, and predictions towards emphasising
71
- insightful points. DPG enables graph-based evaluations and the identification of model decisions
72
- towards facilitating comparisons between features and their associated values while offering insights
73
- into the entire model. DPG provides descriptive metrics that enhance the understanding of the
74
- decisions inherent in the model, offering valuable insights.
75
- <p align="center">
76
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/image.png" width="600" />
77
- </p>
78
-
79
- ---
80
-
81
- ## At a glance
82
-
83
- - High-level API for global and local explanation with `DPGExplainer`
84
- - Graph-based metrics such as constraints, betweenness centrality, and local reaching centrality
85
- - Local path inspection, local-on-global visualization, and faithfulness diagnostics
86
- - Lightweight experiment runners and analysis utilities for sklearn datasets
87
-
88
- ## Quick links
89
-
90
- - Installation: [Installation](#installation)
91
- - High-level usage: [High-level usage](#high-level-usage)
92
- - Local explanations: [Local explanations](#local-explanations)
93
- - Faithfulness evaluation: [Faithfulness evaluation](#faithfulness-evaluation)
94
- - Visualizations: [https://dpg.readthedocs.io/en/latest/visualization.html](https://dpg.readthedocs.io/en/latest/visualization.html)
95
- - CLI usage and gallery examples: [CLI scripts](#cli-scripts)
96
- - Full docs: [https://dpg.readthedocs.io/](https://dpg.readthedocs.io/)
97
-
98
- ## How DPG works
99
- The concept behind DPG is to convert a generic tree-based ensemble model for classification into a graph, where:
100
- - Nodes represent predicates, i.e., the feature-value associations present in each node of every tree;
101
- - Edges denote the frequency with which these predicates are satisfied during the model training phase by the samples of the dataset.
102
-
103
- <p align="center">
104
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example.png" width="600" />
105
- </p>
106
-
107
- ## Metrics
108
- The graph-based nature of DPG provides significant enhancements in the direction of a complete mapping of the ensemble structure.
109
- | Property | Definition | Utility |
110
- |--------------|------------|---------|
111
- | _Constraints_ | The intervals of values for each feature obtained from all predicates connected by a path that culminates in a given class. | Calculate the classification boundary values of each feature associated with each class. |
112
- | _Betweenness centrality_ | Quantifies the fraction of all the shortest paths between every pair of nodes of the graph passing through the considered node. | Identify potential bottleneck nodes that correspond to crucial decisions. |
113
- | _Local reaching centrality_ | Quantifies the proportion of other nodes reachable from the local node through its outgoing edges. | Assess the importance of nodes similarly to feature importance, but enrich the information by encompassing the values associated with features across all decisions. |
114
- | _Community_ | A subset of nodes of the DPG which is characterised by dense interconnections between its elements and sparse connections with the other nodes of the DPG that do not belong to the community. | Understanding the characteristics of nodes to be assigned to a particular community class, identifying predominant predicates, and those that play a marginal role in the classification process. |
115
-
116
-
117
- |Constraints | Betweenness centrality | Local reaching centrality | Community|
118
- |------------|------------|--------------|--------------------|
119
- ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_constraints.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_bc.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_lrc.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_community.png) |
120
- |Constraints(Class 1) = val3 < F1 ≤ val1, F2 ≤ val2 | BC(F2 ≤ val2) = 4/24 | LRC(F1 ≤ val1) = 6 / 7 | Community(Class 1) = F1 ≤ val1, F2 ≤ val2 |
121
-
122
- ---
123
- ## Installation
124
-
125
- Install the package from PyPI:
126
-
127
- ```bash
128
- pip install dpg
129
- ```
130
-
131
- DPG requires Python 3.10+.
132
-
133
- If you want graph rendering, install the system Graphviz package as well so the
134
- `dot` executable is available on your `PATH`:
135
-
136
- - macOS (Homebrew): `brew install graphviz`
137
- - Ubuntu/Debian: `sudo apt-get install graphviz`
138
- - Windows (winget): `winget install Graphviz.Graphviz`
139
-
140
- For local development installs, editable mode, and documentation builds, see
141
- [docs/README.md](docs/README.md).
142
- ---
143
-
144
- ## Documentation
145
-
146
- For full documentation, visit [https://dpg.readthedocs.io/](https://dpg.readthedocs.io/).
147
-
148
- To build and serve documentation locally, see [docs/README.md](docs/README.md).
149
-
150
- Practitioner-focused benchmark material for `perc_var` and `decimal_threshold` is available in
151
- [tutorials/parameter_sensitivity_benchmark/README.md](tutorials/parameter_sensitivity_benchmark/README.md).
152
-
153
- ---
154
-
155
- ## High-level usage
156
-
157
- Here is a minimal high-level example:
158
-
159
- ```python
160
- import pandas as pd
161
- import numpy as np
162
- from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
163
- from dpg import DPGExplainer
164
-
165
- # Load dataset (last column assumed to be target)
166
- df = pd.read_csv("datasets/custom.csv", index_col=0)
167
- X = df.iloc[:, :-1]
168
- y = df.iloc[:, -1]
169
-
170
- # Train a classifier (supports RandomForest, GradientBoosting, AdaBoost, ExtraTree, and more)
171
- model = RandomForestClassifier(n_estimators=10, random_state=27)
172
- # or: model = GradientBoostingClassifier(n_estimators=10, random_state=27)
173
- model.fit(X, y)
174
-
175
- # Build the DPG and extract global explanations
176
- explainer = DPGExplainer(
177
- model=model,
178
- feature_names=X.columns,
179
- target_names=np.unique(y).astype(str).tolist(),
180
- )
181
- explanation = explainer.explain_global(X.values, communities=True)
182
-
183
- # Render the graph to disk
184
- explainer.plot("dpg_output", explanation, save_dir="datasets", export_pdf=True)
185
- explainer.plot_communities("dpg_output", explanation, save_dir="datasets", export_pdf=True)
186
- ```
187
-
188
- ### Common workflows
189
-
190
- The high-level API is designed to return structured outputs so downstream tools can use them directly.
191
-
192
- - `DPGExplainer.fit(X)`: builds the DPG structure
193
- - `DPGExplainer.explain_global(X=None, communities=False, community_threshold=0.2)`: returns a `DPGExplanation`
194
- - `DPGExplainer.explain_local(sample, sample_id=0, X=None, validate_graph=True)`: returns a `DPGLocalExplanation`
195
- - `DPGExplainer.local_path_dataframe(local_explanation)`: flattens local paths into a tabular view
196
- - `DPGExplainer.plot(...)`: renders the standard DPG
197
- - `DPGExplainer.plot_communities(...)`: renders a community-colored DPG
198
- - `DPGExplainer.plot_local_on_dpg(...)`: overlays one sample's local paths on the fitted DPG
199
- - `DPGExplainer.evaluate_faithfulness(...)`: summarizes local explanation fidelity and structural faithfulness over a dataset
200
-
201
- `DPGExplanation` includes `dot`, `graph`, `nodes`, `node_metrics`, `edge_metrics`, `class_boundaries`, and optional `communities`.
202
-
203
- ### Local explanations
204
-
205
- DPG also supports sample-level explanations on top of the fitted global graph.
206
-
207
- #### Graph construction modes
208
-
209
- You can control how the graph is built through `dpg.graph_construction.mode`:
210
-
211
- ```python
212
- from dpg import DPGExplainer
213
-
214
- explainer = DPGExplainer(
215
- model=model,
216
- feature_names=X.columns.tolist(),
217
- target_names=class_names,
218
- dpg_config={
219
- "dpg": {
220
- "default": {
221
- "perc_var": 1e-9,
222
- "decimal_threshold": 6,
223
- "n_jobs": -1,
224
- },
225
- "graph_construction": {
226
- "mode": "execution_trace", # or "aggregated_transitions"
227
- "context_order": 1, # 1, an integer > 1, or "auto"
228
- },
229
- }
230
- },
231
- )
232
- ```
233
-
234
- - `"aggregated_transitions"`: current default behavior; filters path variants first, then discovers the DPG.
235
- - `"execution_trace"`: builds directly from raw traces and filters edges instead of whole-path variants when `perc_var > 0`.
236
-
237
- `context_order` controls predicate identity in `execution_trace` mode. `1`
238
- preserves the legacy graph exactly; an order greater than one uses the last k
239
- executed predicates as context and keeps one sink per class. `"auto"` resolves
240
- the smallest order for which every pooled graph path is supported by an
241
- observed execution trace, including recombinations that only appear after
242
- multiple hops. Orders greater than one require `mode: "execution_trace"`.
243
- `context_order="auto"` also requires `execution_trace`; in
244
- `aggregated_transitions` mode context resolution is not applied.
245
-
246
- A phantom path is a multi-hop path assembled by pooling edges from different
247
- tree executions even though no single execution produced it. DPG-k removes
248
- these recombinations at the resolved context order while retaining one graph.
249
- The effective order and each node's context are available through
250
- `get_context_order()` and `get_node_context(node)`.
251
-
252
- **Regression scope (0.3.0):** `context_order` builds without raising for
253
- regressors (regression leaves, labeled `"Pred <value>"`, are treated as
254
- terminal sinks just like class leaves), but "one sink per output" is not a
255
- defined guarantee for regression the way it is for classification: two
256
- leaves collapse into the same sink only when their rounded values coincide,
257
- which is an artifact of label rounding, not a modeled invariant. A
258
- principled regression sink policy is deferred past 0.3.0. `class_boundaries`
259
- and `communities` remain classifier-only; calling `explain_global`
260
- with `communities=True` on a regressor raises a clear `ValueError`.
261
-
262
- #### Minimal local workflow
263
-
264
- ```python
265
- from sklearn.datasets import load_iris
266
- from sklearn.ensemble import RandomForestClassifier
267
- from dpg import DPGExplainer
268
- import numpy as np
269
-
270
- X, y = load_iris(return_X_y=True, as_frame=True)
271
- model = RandomForestClassifier(n_estimators=5, random_state=42).fit(X, y)
272
-
273
- explainer = DPGExplainer(
274
- model=model,
275
- feature_names=X.columns.tolist(),
276
- target_names=np.unique(y).astype(str).tolist(),
277
- )
278
- explainer.fit(X.values)
279
-
280
- local = explainer.explain_local(sample=X.iloc[0].values, sample_id=0)
281
-
282
- print(local.majority_vote)
283
- print(local.class_votes)
284
- print(local.sample_confidence)
285
-
286
- df_local = explainer.local_path_dataframe(local)
287
- print(df_local.head())
288
- ```
289
-
290
- `local.tree_paths[*].labels` stay in DPG label format such as `"sepal width (cm) <= 3.0"` and `"Class 0"`.
291
- For easier aggregation, `local.class_votes` and `local.majority_vote` use normalized class names such as `"0"` instead of `"Class 0"`.
292
-
293
- #### Local plotting
294
-
295
- ```python
296
- explainer.plot_local_on_dpg(
297
- "iris_local_sample0",
298
- local_explanation=local,
299
- true_class_label=str(y.iloc[0]),
300
- save_dir="results/",
301
- theme="dpg",
302
- palette="olive",
303
- layout_template="vertical",
304
- show=False,
305
- )
306
- ```
307
-
308
- A runnable example is available at [examples/local_explanation_iris.py](examples/local_explanation_iris.py).
309
-
310
- #### Faithfulness evaluation
311
-
312
- You can also evaluate local explanations against the fitted black-box model:
313
-
314
- ```python
315
- details = explainer.evaluate_faithfulness(
316
- X_test,
317
- y_true=y_test,
318
- return_details=True,
319
- )
320
-
321
- print(details["faithfulness_score"])
322
- print(details["output_fidelity"])
323
- print(details["mean_trace_coverage_score"])
324
- print(details["mean_recombination_rate"])
325
- ```
326
-
327
- This reports:
328
- - `output_fidelity`: agreement between the local explanation and the black-box model
329
- - structural metrics such as trace coverage and recombination
330
- - semantic metrics such as evidence margin
331
- - a composite `faithfulness_score`
332
-
333
- Important:
334
- - the composite score is a heuristic summary, not a calibrated probability
335
- - `output_fidelity` is model agreement, not ground-truth correctness
336
- - `local_accuracy` is only reported when `y_true` is provided
337
- - structural faithfulness here means recovering the executed decision traces used by the model
338
-
339
- ### Runnable examples
340
-
341
- - [examples/quickstart_iris.py](examples/quickstart_iris.py)
342
- - [examples/local_explanation_iris.py](examples/local_explanation_iris.py)
343
- - [examples](examples)
344
-
345
- ## CLI scripts
346
- The library contains two different scripts to apply DPG:
347
- - `examples/run_dpg_standard.py`: with this script it is possible to test DPG on a standard classification dataset provided by `sklearn` such as `iris`, `digits`, `wine`, `breast cancer`, and `diabetes`.
348
- - `examples/run_dpg_custom.py`: with this script it is possible to apply DPG to your classification dataset, specifying the target class.
349
-
350
- ### Implementation notes
351
- The library also contains two other essential scripts:
352
- - `core.py` contains all the functions used to calculate and create the DPG and the metrics.
353
- - `visualizer.py` contains the functions used to manage the visualization of DPG.
354
-
355
- ### Output
356
- The DPG output, through `examples/run_dpg_standard.py` or `examples/run_dpg_custom.py`, produces several files:
357
- - the visualization of DPG in a dedicated environment, which can be zoomed and saved;
358
- - a `.txt` file containing the DPG metrics;
359
- - a `.csv` file containing the information about all the nodes of the DPG and their associated metrics;
360
- - a `.txt` file containing the Random Forest statistics (accuracy, confusion matrix, classification report)
361
-
362
- ### CLI parameter reference
363
- Usage: `dpg --dataset <dataset_name> --n_learners <integer_number> --pv <threshold_value> --t <integer_number> --model_name <str_model_name> --dir <save_dir_path> --plot --save_plot_dir <save_plot_dir_path> --attribute <attribute> --communities --clusters --threshold_clusters <float> --class_flag --seed <int>`
364
-
365
- After installing DPG, the `dpg` command is the packaged equivalent of
366
- `python examples/run_dpg_standard.py`.
367
- Where:
368
- - `dataset` is the name of the standard classification `sklearn` dataset to be analyzed;
369
- - `n_learners` is the number of base learners for the ensemble model;
370
- - `pv` is the threshold value indicating the desire to retain only those paths that occur with a frequency exceeding a specified proportion across the trees;
371
- - `t` is the decimal precision of each feature;
372
- - `model_name` is the name of the `sklearn` model chosen to perform classification. Supported models include:
373
- - `RandomForestClassifier` (default)
374
- - `GradientBoostingClassifier` (new!)
375
- - `RandomForestRegressor`
376
- - `GradientBoostingRegressor`
377
- - `ExtraTreesClassifier`
378
- - `AdaBoostClassifier`
379
- - `AdaBoostRegressor`
380
- - `BaggingClassifier`
381
- - `dir` is the path of the directory to save the files;
382
- - `plot` is a store_true variable which can be added to plot the DPG;
383
- - `save_plot_dir` is the path of the directory to save the plot image;
384
- - `attribute` is the specific node metric which can be visualized on the DPG;
385
- - `communities` is a store_true variable which can be added to visualize communities on the DPG;
386
- - `clusters` is a store_true variable which can be added to visualize clusters on the DPG;
387
- - `threshold_clusters` is the threshold used to detect ambiguous nodes in clusters;
388
- - `class_flag` is a store_true variable which can be added to highlight class nodes;
389
- - `seed` controls the random split.
390
-
391
- Disclaimer: `attribute`, `communities`, and `clusters` are mutually exclusive: DPG supports just one visualization mode at a time.
392
-
393
- The usage of `examples/run_dpg_custom.py` is similar, but it requires another parameter:
394
- - `target_column`, which is the name of the column to be used as the target variable;
395
- - while `ds` is the path of the directory where the dataset is.
396
-
397
- ### Example `examples/run_dpg_standard.py`
398
- Some examples can be appreciated in the `examples` folder: https://github.com/Meta-Group/DPG/tree/main/examples
399
-
400
- In particular, the following DPG is obtained by transforming a Random Forest with 5 base learners, trained on Iris dataset.
401
- The used command is `dpg --dataset iris --n_learners 5 --pv 0.001 --t 2 --dir examples --plot --save_plot_dir examples`.
402
- <p align="center">
403
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/iris_bl5_perc0.001_dec2.png" width="800" />
404
- </p>
405
-
406
- The following visualizations are obtained using the same parameters as the previous example, but they show two different metrics: _Community_ and _Betweenness centrality_.
407
- The used command for showing communities is `dpg --dataset iris --n_learners 5 --pv 0.001 --t 2 --dir examples --plot --save_plot_dir examples --communities`.
408
- <p align="center">
409
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/iris_bl5_perc0.001_dec2_communities.png" width="800" />
410
- </p>
411
-
412
- The used command for showing a specific property is `dpg --dataset iris --n_learners 5 --pv 0.001 --t 2 --dir examples --plot --save_plot_dir examples --attribute "Betweenness centrality" --class_flag`.
413
- <p align="center">
414
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/iris_bl5_perc0.001_dec2_Betweennesscentrality.png" width="800" />
415
- </p>
416
-
417
- ***
418
- ## Citation
419
- If you use this for research, please cite. Here is an example BibTeX entry:
420
-
421
- ```bibtex
422
- @inproceedings{arrighi2024dpg,
423
- title={Decision Predicate Graphs: Enhancing Interpretability in Tree Ensembles},
424
- author={Arrighi, Leonardo and Pennella, Luca and Marques Tavares, Gabriel and Barbon Junior, Sylvio},
425
- booktitle={World Conference on Explainable Artificial Intelligence},
426
- pages={311--332},
427
- year={2024},
428
- isbn = {978-3-031-63797-1},
429
- doi = {10.1007/978-3-031-63797-1_16},
430
- publisher = {Springer Nature Switzerland},
431
- }
432
-
dpg-0.3.3/README.md DELETED
@@ -1,379 +0,0 @@
1
- # Decision Predicate Graph (DPG)
2
-
3
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
4
- [![Python Versions](https://img.shields.io/badge/python-3.10%20|%203.11%20|%203.12-blue.svg)](pyproject.toml)
5
- [![Build Status](https://github.com/Meta-Group/DPG/actions/workflows/tests.yml/badge.svg)](https://github.com/Meta-Group/DPG/actions/workflows/tests.yml)
6
- [![Documentation Status](https://readthedocs.org/projects/dpg/badge/?version=latest)](https://dpg.readthedocs.io/en/latest/)
7
-
8
- <p align="center">
9
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/DPG.png" alt="DPG logo" width="300">
10
- </p>
11
-
12
-
13
- DPG is a model-agnostic framework for global and local explanation of tree-based ensemble models.
14
- It turns ensemble decision logic into a graph so users can inspect predicates, transitions, predictions,
15
- and structural explanation diagnostics in a single representation.
16
-
17
- DPG is a graph structure that captures the tree-based ensemble model and learned dataset details,
18
- preserving the relations among features, logical decisions, and predictions towards emphasising
19
- insightful points. DPG enables graph-based evaluations and the identification of model decisions
20
- towards facilitating comparisons between features and their associated values while offering insights
21
- into the entire model. DPG provides descriptive metrics that enhance the understanding of the
22
- decisions inherent in the model, offering valuable insights.
23
- <p align="center">
24
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/image.png" width="600" />
25
- </p>
26
-
27
- ---
28
-
29
- ## At a glance
30
-
31
- - High-level API for global and local explanation with `DPGExplainer`
32
- - Graph-based metrics such as constraints, betweenness centrality, and local reaching centrality
33
- - Local path inspection, local-on-global visualization, and faithfulness diagnostics
34
- - Lightweight experiment runners and analysis utilities for sklearn datasets
35
-
36
- ## Quick links
37
-
38
- - Installation: [Installation](#installation)
39
- - High-level usage: [High-level usage](#high-level-usage)
40
- - Local explanations: [Local explanations](#local-explanations)
41
- - Faithfulness evaluation: [Faithfulness evaluation](#faithfulness-evaluation)
42
- - Visualizations: [https://dpg.readthedocs.io/en/latest/visualization.html](https://dpg.readthedocs.io/en/latest/visualization.html)
43
- - CLI usage and gallery examples: [CLI scripts](#cli-scripts)
44
- - Full docs: [https://dpg.readthedocs.io/](https://dpg.readthedocs.io/)
45
-
46
- ## How DPG works
47
- The concept behind DPG is to convert a generic tree-based ensemble model for classification into a graph, where:
48
- - Nodes represent predicates, i.e., the feature-value associations present in each node of every tree;
49
- - Edges denote the frequency with which these predicates are satisfied during the model training phase by the samples of the dataset.
50
-
51
- <p align="center">
52
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example.png" width="600" />
53
- </p>
54
-
55
- ## Metrics
56
- The graph-based nature of DPG provides significant enhancements in the direction of a complete mapping of the ensemble structure.
57
- | Property | Definition | Utility |
58
- |--------------|------------|---------|
59
- | _Constraints_ | The intervals of values for each feature obtained from all predicates connected by a path that culminates in a given class. | Calculate the classification boundary values of each feature associated with each class. |
60
- | _Betweenness centrality_ | Quantifies the fraction of all the shortest paths between every pair of nodes of the graph passing through the considered node. | Identify potential bottleneck nodes that correspond to crucial decisions. |
61
- | _Local reaching centrality_ | Quantifies the proportion of other nodes reachable from the local node through its outgoing edges. | Assess the importance of nodes similarly to feature importance, but enrich the information by encompassing the values associated with features across all decisions. |
62
- | _Community_ | A subset of nodes of the DPG which is characterised by dense interconnections between its elements and sparse connections with the other nodes of the DPG that do not belong to the community. | Understanding the characteristics of nodes to be assigned to a particular community class, identifying predominant predicates, and those that play a marginal role in the classification process. |
63
-
64
-
65
- |Constraints | Betweenness centrality | Local reaching centrality | Community|
66
- |------------|------------|--------------|--------------------|
67
- ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_constraints.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_bc.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_lrc.png) | ![](https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/example_community.png) |
68
- |Constraints(Class 1) = val3 < F1 ≤ val1, F2 ≤ val2 | BC(F2 ≤ val2) = 4/24 | LRC(F1 ≤ val1) = 6 / 7 | Community(Class 1) = F1 ≤ val1, F2 ≤ val2 |
69
-
70
- ---
71
- ## Installation
72
-
73
- Install the package from PyPI:
74
-
75
- ```bash
76
- pip install dpg
77
- ```
78
-
79
- DPG requires Python 3.10+.
80
-
81
- If you want graph rendering, install the system Graphviz package as well so the
82
- `dot` executable is available on your `PATH`:
83
-
84
- - macOS (Homebrew): `brew install graphviz`
85
- - Ubuntu/Debian: `sudo apt-get install graphviz`
86
- - Windows (winget): `winget install Graphviz.Graphviz`
87
-
88
- For local development installs, editable mode, and documentation builds, see
89
- [docs/README.md](docs/README.md).
90
- ---
91
-
92
- ## Documentation
93
-
94
- For full documentation, visit [https://dpg.readthedocs.io/](https://dpg.readthedocs.io/).
95
-
96
- To build and serve documentation locally, see [docs/README.md](docs/README.md).
97
-
98
- Practitioner-focused benchmark material for `perc_var` and `decimal_threshold` is available in
99
- [tutorials/parameter_sensitivity_benchmark/README.md](tutorials/parameter_sensitivity_benchmark/README.md).
100
-
101
- ---
102
-
103
- ## High-level usage
104
-
105
- Here is a minimal high-level example:
106
-
107
- ```python
108
- import pandas as pd
109
- import numpy as np
110
- from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
111
- from dpg import DPGExplainer
112
-
113
- # Load dataset (last column assumed to be target)
114
- df = pd.read_csv("datasets/custom.csv", index_col=0)
115
- X = df.iloc[:, :-1]
116
- y = df.iloc[:, -1]
117
-
118
- # Train a classifier (supports RandomForest, GradientBoosting, AdaBoost, ExtraTree, and more)
119
- model = RandomForestClassifier(n_estimators=10, random_state=27)
120
- # or: model = GradientBoostingClassifier(n_estimators=10, random_state=27)
121
- model.fit(X, y)
122
-
123
- # Build the DPG and extract global explanations
124
- explainer = DPGExplainer(
125
- model=model,
126
- feature_names=X.columns,
127
- target_names=np.unique(y).astype(str).tolist(),
128
- )
129
- explanation = explainer.explain_global(X.values, communities=True)
130
-
131
- # Render the graph to disk
132
- explainer.plot("dpg_output", explanation, save_dir="datasets", export_pdf=True)
133
- explainer.plot_communities("dpg_output", explanation, save_dir="datasets", export_pdf=True)
134
- ```
135
-
136
- ### Common workflows
137
-
138
- The high-level API is designed to return structured outputs so downstream tools can use them directly.
139
-
140
- - `DPGExplainer.fit(X)`: builds the DPG structure
141
- - `DPGExplainer.explain_global(X=None, communities=False, community_threshold=0.2)`: returns a `DPGExplanation`
142
- - `DPGExplainer.explain_local(sample, sample_id=0, X=None, validate_graph=True)`: returns a `DPGLocalExplanation`
143
- - `DPGExplainer.local_path_dataframe(local_explanation)`: flattens local paths into a tabular view
144
- - `DPGExplainer.plot(...)`: renders the standard DPG
145
- - `DPGExplainer.plot_communities(...)`: renders a community-colored DPG
146
- - `DPGExplainer.plot_local_on_dpg(...)`: overlays one sample's local paths on the fitted DPG
147
- - `DPGExplainer.evaluate_faithfulness(...)`: summarizes local explanation fidelity and structural faithfulness over a dataset
148
-
149
- `DPGExplanation` includes `dot`, `graph`, `nodes`, `node_metrics`, `edge_metrics`, `class_boundaries`, and optional `communities`.
150
-
151
- ### Local explanations
152
-
153
- DPG also supports sample-level explanations on top of the fitted global graph.
154
-
155
- #### Graph construction modes
156
-
157
- You can control how the graph is built through `dpg.graph_construction.mode`:
158
-
159
- ```python
160
- from dpg import DPGExplainer
161
-
162
- explainer = DPGExplainer(
163
- model=model,
164
- feature_names=X.columns.tolist(),
165
- target_names=class_names,
166
- dpg_config={
167
- "dpg": {
168
- "default": {
169
- "perc_var": 1e-9,
170
- "decimal_threshold": 6,
171
- "n_jobs": -1,
172
- },
173
- "graph_construction": {
174
- "mode": "execution_trace", # or "aggregated_transitions"
175
- "context_order": 1, # 1, an integer > 1, or "auto"
176
- },
177
- }
178
- },
179
- )
180
- ```
181
-
182
- - `"aggregated_transitions"`: current default behavior; filters path variants first, then discovers the DPG.
183
- - `"execution_trace"`: builds directly from raw traces and filters edges instead of whole-path variants when `perc_var > 0`.
184
-
185
- `context_order` controls predicate identity in `execution_trace` mode. `1`
186
- preserves the legacy graph exactly; an order greater than one uses the last k
187
- executed predicates as context and keeps one sink per class. `"auto"` resolves
188
- the smallest order for which every pooled graph path is supported by an
189
- observed execution trace, including recombinations that only appear after
190
- multiple hops. Orders greater than one require `mode: "execution_trace"`.
191
- `context_order="auto"` also requires `execution_trace`; in
192
- `aggregated_transitions` mode context resolution is not applied.
193
-
194
- A phantom path is a multi-hop path assembled by pooling edges from different
195
- tree executions even though no single execution produced it. DPG-k removes
196
- these recombinations at the resolved context order while retaining one graph.
197
- The effective order and each node's context are available through
198
- `get_context_order()` and `get_node_context(node)`.
199
-
200
- **Regression scope (0.3.0):** `context_order` builds without raising for
201
- regressors (regression leaves, labeled `"Pred <value>"`, are treated as
202
- terminal sinks just like class leaves), but "one sink per output" is not a
203
- defined guarantee for regression the way it is for classification: two
204
- leaves collapse into the same sink only when their rounded values coincide,
205
- which is an artifact of label rounding, not a modeled invariant. A
206
- principled regression sink policy is deferred past 0.3.0. `class_boundaries`
207
- and `communities` remain classifier-only; calling `explain_global`
208
- with `communities=True` on a regressor raises a clear `ValueError`.
209
-
210
- #### Minimal local workflow
211
-
212
- ```python
213
- from sklearn.datasets import load_iris
214
- from sklearn.ensemble import RandomForestClassifier
215
- from dpg import DPGExplainer
216
- import numpy as np
217
-
218
- X, y = load_iris(return_X_y=True, as_frame=True)
219
- model = RandomForestClassifier(n_estimators=5, random_state=42).fit(X, y)
220
-
221
- explainer = DPGExplainer(
222
- model=model,
223
- feature_names=X.columns.tolist(),
224
- target_names=np.unique(y).astype(str).tolist(),
225
- )
226
- explainer.fit(X.values)
227
-
228
- local = explainer.explain_local(sample=X.iloc[0].values, sample_id=0)
229
-
230
- print(local.majority_vote)
231
- print(local.class_votes)
232
- print(local.sample_confidence)
233
-
234
- df_local = explainer.local_path_dataframe(local)
235
- print(df_local.head())
236
- ```
237
-
238
- `local.tree_paths[*].labels` stay in DPG label format such as `"sepal width (cm) <= 3.0"` and `"Class 0"`.
239
- For easier aggregation, `local.class_votes` and `local.majority_vote` use normalized class names such as `"0"` instead of `"Class 0"`.
240
-
241
- #### Local plotting
242
-
243
- ```python
244
- explainer.plot_local_on_dpg(
245
- "iris_local_sample0",
246
- local_explanation=local,
247
- true_class_label=str(y.iloc[0]),
248
- save_dir="results/",
249
- theme="dpg",
250
- palette="olive",
251
- layout_template="vertical",
252
- show=False,
253
- )
254
- ```
255
-
256
- A runnable example is available at [examples/local_explanation_iris.py](examples/local_explanation_iris.py).
257
-
258
- #### Faithfulness evaluation
259
-
260
- You can also evaluate local explanations against the fitted black-box model:
261
-
262
- ```python
263
- details = explainer.evaluate_faithfulness(
264
- X_test,
265
- y_true=y_test,
266
- return_details=True,
267
- )
268
-
269
- print(details["faithfulness_score"])
270
- print(details["output_fidelity"])
271
- print(details["mean_trace_coverage_score"])
272
- print(details["mean_recombination_rate"])
273
- ```
274
-
275
- This reports:
276
- - `output_fidelity`: agreement between the local explanation and the black-box model
277
- - structural metrics such as trace coverage and recombination
278
- - semantic metrics such as evidence margin
279
- - a composite `faithfulness_score`
280
-
281
- Important:
282
- - the composite score is a heuristic summary, not a calibrated probability
283
- - `output_fidelity` is model agreement, not ground-truth correctness
284
- - `local_accuracy` is only reported when `y_true` is provided
285
- - structural faithfulness here means recovering the executed decision traces used by the model
286
-
287
- ### Runnable examples
288
-
289
- - [examples/quickstart_iris.py](examples/quickstart_iris.py)
290
- - [examples/local_explanation_iris.py](examples/local_explanation_iris.py)
291
- - [examples](examples)
292
-
293
- ## CLI scripts
294
- The library contains two different scripts to apply DPG:
295
- - `examples/run_dpg_standard.py`: with this script it is possible to test DPG on a standard classification dataset provided by `sklearn` such as `iris`, `digits`, `wine`, `breast cancer`, and `diabetes`.
296
- - `examples/run_dpg_custom.py`: with this script it is possible to apply DPG to your classification dataset, specifying the target class.
297
-
298
- ### Implementation notes
299
- The library also contains two other essential scripts:
300
- - `core.py` contains all the functions used to calculate and create the DPG and the metrics.
301
- - `visualizer.py` contains the functions used to manage the visualization of DPG.
302
-
303
- ### Output
304
- The DPG output, through `examples/run_dpg_standard.py` or `examples/run_dpg_custom.py`, produces several files:
305
- - the visualization of DPG in a dedicated environment, which can be zoomed and saved;
306
- - a `.txt` file containing the DPG metrics;
307
- - a `.csv` file containing the information about all the nodes of the DPG and their associated metrics;
308
- - a `.txt` file containing the Random Forest statistics (accuracy, confusion matrix, classification report)
309
-
310
- ### CLI parameter reference
311
- Usage: `dpg --dataset <dataset_name> --n_learners <integer_number> --pv <threshold_value> --t <integer_number> --model_name <str_model_name> --dir <save_dir_path> --plot --save_plot_dir <save_plot_dir_path> --attribute <attribute> --communities --clusters --threshold_clusters <float> --class_flag --seed <int>`
312
-
313
- After installing DPG, the `dpg` command is the packaged equivalent of
314
- `python examples/run_dpg_standard.py`.
315
- Where:
316
- - `dataset` is the name of the standard classification `sklearn` dataset to be analyzed;
317
- - `n_learners` is the number of base learners for the ensemble model;
318
- - `pv` is the threshold value indicating the desire to retain only those paths that occur with a frequency exceeding a specified proportion across the trees;
319
- - `t` is the decimal precision of each feature;
320
- - `model_name` is the name of the `sklearn` model chosen to perform classification. Supported models include:
321
- - `RandomForestClassifier` (default)
322
- - `GradientBoostingClassifier` (new!)
323
- - `RandomForestRegressor`
324
- - `GradientBoostingRegressor`
325
- - `ExtraTreesClassifier`
326
- - `AdaBoostClassifier`
327
- - `AdaBoostRegressor`
328
- - `BaggingClassifier`
329
- - `dir` is the path of the directory to save the files;
330
- - `plot` is a store_true variable which can be added to plot the DPG;
331
- - `save_plot_dir` is the path of the directory to save the plot image;
332
- - `attribute` is the specific node metric which can be visualized on the DPG;
333
- - `communities` is a store_true variable which can be added to visualize communities on the DPG;
334
- - `clusters` is a store_true variable which can be added to visualize clusters on the DPG;
335
- - `threshold_clusters` is the threshold used to detect ambiguous nodes in clusters;
336
- - `class_flag` is a store_true variable which can be added to highlight class nodes;
337
- - `seed` controls the random split.
338
-
339
- Disclaimer: `attribute`, `communities`, and `clusters` are mutually exclusive: DPG supports just one visualization mode at a time.
340
-
341
- The usage of `examples/run_dpg_custom.py` is similar, but it requires another parameter:
342
- - `target_column`, which is the name of the column to be used as the target variable;
343
- - while `ds` is the path of the directory where the dataset is.
344
-
345
- ### Example `examples/run_dpg_standard.py`
346
- Some examples can be appreciated in the `examples` folder: https://github.com/Meta-Group/DPG/tree/main/examples
347
-
348
- In particular, the following DPG is obtained by transforming a Random Forest with 5 base learners, trained on Iris dataset.
349
- The used command is `dpg --dataset iris --n_learners 5 --pv 0.001 --t 2 --dir examples --plot --save_plot_dir examples`.
350
- <p align="center">
351
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/iris_bl5_perc0.001_dec2.png" width="800" />
352
- </p>
353
-
354
- The following visualizations are obtained using the same parameters as the previous example, but they show two different metrics: _Community_ and _Betweenness centrality_.
355
- The used command for showing communities is `dpg --dataset iris --n_learners 5 --pv 0.001 --t 2 --dir examples --plot --save_plot_dir examples --communities`.
356
- <p align="center">
357
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/iris_bl5_perc0.001_dec2_communities.png" width="800" />
358
- </p>
359
-
360
- The used command for showing a specific property is `dpg --dataset iris --n_learners 5 --pv 0.001 --t 2 --dir examples --plot --save_plot_dir examples --attribute "Betweenness centrality" --class_flag`.
361
- <p align="center">
362
- <img src="https://raw.githubusercontent.com/Meta-Group/DPG/main/dpg_image_examples/iris_bl5_perc0.001_dec2_Betweennesscentrality.png" width="800" />
363
- </p>
364
-
365
- ***
366
- ## Citation
367
- If you use this for research, please cite. Here is an example BibTeX entry:
368
-
369
- ```bibtex
370
- @inproceedings{arrighi2024dpg,
371
- title={Decision Predicate Graphs: Enhancing Interpretability in Tree Ensembles},
372
- author={Arrighi, Leonardo and Pennella, Luca and Marques Tavares, Gabriel and Barbon Junior, Sylvio},
373
- booktitle={World Conference on Explainable Artificial Intelligence},
374
- pages={311--332},
375
- year={2024},
376
- isbn = {978-3-031-63797-1},
377
- doi = {10.1007/978-3-031-63797-1_16},
378
- publisher = {Springer Nature Switzerland},
379
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes