fast-causal-shap 0.1.0__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.

Potentially problematic release.


This version of fast-causal-shap might be problematic. Click here for more details.

@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [year] [fullname]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: fast-causal-shap
3
+ Version: 0.1.0
4
+ Summary: A Python package for efficient causal SHAP computations
5
+ Author-email: woonyee28 <ngnwy289@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/woonyee28/CausalSHAP
8
+ Project-URL: Issues, https://github.com/woonyee28/CausalSHAP/issues
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pandas>=1.0.0
13
+ Requires-Dist: networkx>=2.0
14
+ Requires-Dist: numpy>=1.18.0
15
+ Requires-Dist: scikit-learn>=0.24.0
16
+ Dynamic: license-file
17
+
18
+ # Fast Causal SHAP
19
+
20
+ This folder contains the core modules and components for the **Fast Causal SHAP** Python package. Fast Causal SHAP provides efficient and interpretable SHAP value computation for causal inference tasks.
21
+
22
+ ## Features
23
+
24
+ - Fast computation of SHAP values for causal models
25
+ - Support for multiple causal inference frameworks
26
+
27
+ ## Installation
28
+
29
+ Install Fast Causal SHAP using pip:
30
+
31
+ ```bash
32
+ pip install fast-causal-shap
33
+ ```
34
+
35
+ Or, for the latest development version:
36
+
37
+ ```bash
38
+ pip install git+https://github.com/woonyee28/CausalSHAP.git
39
+ ```
40
+
41
+ ## Usage
42
+ // To be added
43
+
44
+ ## Citation
45
+ If you use this package in your research, please cite:
46
+ // To be added
47
+
48
+ ## License
49
+
50
+ This project is licensed under the MIT License.
@@ -0,0 +1,33 @@
1
+ # Fast Causal SHAP
2
+
3
+ This folder contains the core modules and components for the **Fast Causal SHAP** Python package. Fast Causal SHAP provides efficient and interpretable SHAP value computation for causal inference tasks.
4
+
5
+ ## Features
6
+
7
+ - Fast computation of SHAP values for causal models
8
+ - Support for multiple causal inference frameworks
9
+
10
+ ## Installation
11
+
12
+ Install Fast Causal SHAP using pip:
13
+
14
+ ```bash
15
+ pip install fast-causal-shap
16
+ ```
17
+
18
+ Or, for the latest development version:
19
+
20
+ ```bash
21
+ pip install git+https://github.com/woonyee28/CausalSHAP.git
22
+ ```
23
+
24
+ ## Usage
25
+ // To be added
26
+
27
+ ## Citation
28
+ If you use this package in your research, please cite:
29
+ // To be added
30
+
31
+ ## License
32
+
33
+ This project is licensed under the MIT License.
@@ -0,0 +1,9 @@
1
+ """Fast Causal SHAP - A Python package for efficient causal SHAP computations."""
2
+
3
+ from .core import FastCausalSHAP
4
+
5
+ __version__ = "0.1.0"
6
+ __author__ = "woonyee28"
7
+ __email__ = "ngnwy289@gmail.com"
8
+
9
+ __all__ = ["FastCausalSHAP"]
@@ -0,0 +1,301 @@
1
+ import pandas as pd
2
+ import networkx as nx
3
+ import numpy as np
4
+ import json
5
+ from math import factorial
6
+ from sklearn.linear_model import LinearRegression
7
+ from collections import defaultdict
8
+
9
+ class FastCausalSHAP:
10
+ def __init__(self, data, model, target_variable):
11
+ self.data = data
12
+ self.model = model
13
+ self.gamma = None
14
+ self.target_variable = target_variable
15
+ self.ida_graph = None
16
+ self.regression_models = {}
17
+ self.feature_depths = {}
18
+ self.path_cache = {}
19
+ self.causal_paths = {}
20
+
21
+ def remove_cycles(self):
22
+ """
23
+ Detects cycles in the graph and removes edges causing cycles.
24
+ Returns a list of removed edges.
25
+ """
26
+ G = self.ida_graph.copy()
27
+ removed_edges = []
28
+
29
+ # Find all cycles in the graph
30
+ try:
31
+ cycles = list(nx.simple_cycles(G))
32
+ except nx.NetworkXNoCycle:
33
+ return [] # No cycles found
34
+
35
+ while cycles:
36
+ # Get the current cycle
37
+ cycle = cycles[0]
38
+
39
+ # Find the edge with the smallest weight in the cycle
40
+ min_weight = float('inf')
41
+ edge_to_remove = None
42
+
43
+ for i in range(len(cycle)):
44
+ source = cycle[i]
45
+ target = cycle[(i + 1) % len(cycle)]
46
+
47
+ if G.has_edge(source, target):
48
+ weight = abs(G[source][target]['weight'])
49
+ if weight < min_weight:
50
+ min_weight = weight
51
+ edge_to_remove = (source, target)
52
+
53
+ if edge_to_remove:
54
+ # Remove the edge with the smallest weight
55
+ G.remove_edge(*edge_to_remove)
56
+ removed_edges.append((edge_to_remove[0], edge_to_remove[1], self.ida_graph[edge_to_remove[0]][edge_to_remove[1]]['weight']))
57
+
58
+ # Recalculate cycles after removing an edge
59
+ try:
60
+ cycles = list(nx.simple_cycles(G))
61
+ except nx.NetworkXNoCycle:
62
+ cycles = [] # No more cycles
63
+ else:
64
+ break
65
+
66
+ # Update the graph
67
+ self.ida_graph = G
68
+ return removed_edges
69
+
70
+ def _compute_causal_paths(self):
71
+ """Compute and store all causal paths to target for each feature."""
72
+ features = [col for col in self.data.columns if col != self.target_variable]
73
+ for feature in features:
74
+ try:
75
+ # Store the actual paths instead of just the features
76
+ paths = list(nx.all_simple_paths(self.ida_graph, feature, self.target_variable))
77
+ self.causal_paths[feature] = paths
78
+ except nx.NetworkXNoPath:
79
+ self.causal_paths[feature] = []
80
+
81
+ def load_causal_strengths(self, json_file_path):
82
+ with open(json_file_path, 'r') as f:
83
+ causal_effects_list = json.load(f)
84
+
85
+ G = nx.DiGraph()
86
+ nodes = list(self.data.columns)
87
+ G.add_nodes_from(nodes)
88
+
89
+ for item in causal_effects_list:
90
+ pair = item['Pair']
91
+ mean_causal_effect = item['Mean_Causal_Effect']
92
+ if mean_causal_effect is None:
93
+ continue
94
+ source, target = pair.split('->')
95
+ source = source.strip()
96
+ target = target.strip()
97
+ G.add_edge(source, target, weight=mean_causal_effect)
98
+ self.ida_graph = G.copy()
99
+
100
+ removed_edges = self.remove_cycles()
101
+ if removed_edges:
102
+ print(f"Removed {len(removed_edges)} edges to make the graph acyclic:")
103
+ for source, target, weight in removed_edges:
104
+ print(f" {source} -> {target} (weight: {weight})")
105
+
106
+ self._compute_feature_depths()
107
+ self._compute_causal_paths()
108
+ features = self.data.columns.tolist()
109
+ beta_dict = {}
110
+
111
+ for feature in features:
112
+ if feature == self.target_variable:
113
+ continue
114
+ try:
115
+ paths = list(nx.all_simple_paths(G, source=feature, target=self.target_variable))
116
+ except nx.NetworkXNoPath:
117
+ continue
118
+ total_effect = 0
119
+ for path in paths:
120
+ effect = 1
121
+ for i in range(len(path)-1):
122
+ edge_weight = G[path[i]][path[i+1]]['weight']
123
+ effect *= edge_weight
124
+ total_effect += effect
125
+ if total_effect != 0:
126
+ beta_dict[feature] = total_effect
127
+
128
+ total_causal_effect = sum(abs(beta) for beta in beta_dict.values())
129
+ if total_causal_effect == 0:
130
+ self.gamma = {k: 0.0 for k in features}
131
+ else:
132
+ self.gamma = {k: abs(beta_dict.get(k, 0.0)) / total_causal_effect for k in features}
133
+ return self.gamma
134
+
135
+ def _compute_feature_depths(self):
136
+ """Compute minimum depth of each feature to target in causal graph."""
137
+ features = [col for col in self.data.columns if col != self.target_variable]
138
+ for feature in features:
139
+ try:
140
+ all_paths = list(nx.all_simple_paths(self.ida_graph, feature, self.target_variable))
141
+ min_depth = float('inf')
142
+ for path in all_paths:
143
+ depth = len(path) - 1
144
+ min_depth = min(min_depth, depth)
145
+ if min_depth != float('inf'):
146
+ self.feature_depths[feature] = min_depth
147
+ except nx.NetworkXNoPath:
148
+ continue
149
+
150
+ def get_topological_order(self, S):
151
+ """Returns the topological order of variables after intervening on subset S."""
152
+ G_intervened = self.ida_graph.copy()
153
+ for feature in S:
154
+ G_intervened.remove_edges_from(list(G_intervened.in_edges(feature)))
155
+ missing_nodes = set(self.data.columns) - set(G_intervened.nodes)
156
+ G_intervened.add_nodes_from(missing_nodes)
157
+
158
+ try:
159
+ order = list(nx.topological_sort(G_intervened))
160
+ except nx.NetworkXUnfeasible:
161
+ raise ValueError("The causal graph contains cycles.")
162
+
163
+ return order
164
+
165
+ def get_parents(self, feature):
166
+ """Returns the list of parent features for a given feature in the causal graph."""
167
+ return list(self.ida_graph.predecessors(feature))
168
+
169
+ def sample_marginal(self, feature):
170
+ """Sample a value from the marginal distribution of the specified feature."""
171
+ return self.data[feature].sample(1).iloc[0]
172
+
173
+ def sample_conditional(self, feature, parent_values):
174
+ """Sample a value for a feature conditioned on its parent features."""
175
+ effective_parents = [p for p in self.get_parents(feature) if p != self.target_variable]
176
+ if not effective_parents:
177
+ return self.sample_marginal(feature)
178
+ model_key = (feature, tuple(sorted(effective_parents)))
179
+ if model_key not in self.regression_models:
180
+ X = self.data[effective_parents].values
181
+ y = self.data[feature].values
182
+ reg = LinearRegression()
183
+ reg.fit(X, y)
184
+ residuals = y - reg.predict(X)
185
+ std = residuals.std()
186
+ self.regression_models[model_key] = (reg, std)
187
+ reg, std = self.regression_models[model_key]
188
+ parent_values_array = np.array([parent_values[parent] for parent in effective_parents]).reshape(1, -1)
189
+ mean = reg.predict(parent_values_array)[0]
190
+ sampled_value = np.random.normal(mean, std)
191
+ return sampled_value
192
+
193
+ def compute_v_do(self, S, x_S, is_classifier=False):
194
+ """Compute interventional expectations with caching."""
195
+ cache_key = (frozenset(S), tuple(sorted(x_S.items())) if len(x_S) > 0 else tuple())
196
+
197
+ if cache_key in self.path_cache:
198
+ return self.path_cache[cache_key]
199
+
200
+ variables_order = self.get_topological_order(S)
201
+
202
+ sample = {}
203
+ for feature in S:
204
+ sample[feature] = x_S[feature]
205
+ for feature in variables_order:
206
+ if feature in S or feature == self.target_variable:
207
+ continue
208
+ parents = self.get_parents(feature)
209
+ parent_values = {p: x_S[p] if p in S else sample[p] for p in parents if p != self.target_variable}
210
+ if not parent_values:
211
+ sample[feature] = self.sample_marginal(feature)
212
+ else:
213
+ sample[feature] = self.sample_conditional(feature, parent_values)
214
+
215
+ intervened_data = pd.DataFrame([sample])
216
+ intervened_data = intervened_data[self.model.feature_names_in_]
217
+ if is_classifier:
218
+ probas = self.model.predict_proba(intervened_data)[:, 1]
219
+ else:
220
+ probas = self.model.predict(intervened_data)
221
+
222
+ result = np.mean(probas)
223
+ self.path_cache[cache_key] = result
224
+ return result
225
+
226
+ def is_on_causal_path(self, feature, S, target_feature):
227
+ """Check if feature is on any causal path from S to target_feature."""
228
+ if target_feature not in self.causal_paths:
229
+ return False
230
+ path_features = self.causal_paths[target_feature]
231
+ return feature in path_features
232
+
233
+ def compute_modified_shap_proba(self, x, is_classifier=False):
234
+ """TreeSHAP-inspired computation using causal paths and dynamic programming."""
235
+ features = [col for col in self.data.columns if col != self.target_variable]
236
+ phi_causal = {feature: 0.0 for feature in features}
237
+
238
+ data_without_target = self.data.drop(columns=[self.target_variable])
239
+ if is_classifier:
240
+ E_fX = self.model.predict_proba(data_without_target)[:, 1].mean()
241
+ else:
242
+ E_fX = self.model.predict(data_without_target).mean()
243
+
244
+ x_ordered = x[self.model.feature_names_in_]
245
+ if is_classifier:
246
+ f_x = self.model.predict_proba(x_ordered.to_frame().T)[0][1]
247
+ else:
248
+ f_x = self.model.predict(x_ordered.to_frame().T)[0]
249
+
250
+ sorted_features = sorted(features, key=lambda f: self.feature_depths.get(f, 0))
251
+ max_path_length = max(self.feature_depths.values(), default=0)
252
+ shapley_weights = {}
253
+ for m in range(max_path_length + 1):
254
+ for d in range(m + 1, max_path_length + 1):
255
+ shapley_weights[(m, d)] = (factorial(m) * factorial(d - m - 1)) / factorial(d)
256
+
257
+ # Track contributions using dynamic programming (EXTEND-like logic in TreeSHAP)
258
+ # m_values will accumulate contributions from subsets (use combinatorial logic)
259
+ # Essentially, values in m_values[k] represent how many ways there are to select k nodes from the path seen so far.
260
+ for feature in sorted_features:
261
+ if feature not in self.causal_paths:
262
+ continue
263
+ for path in self.causal_paths[feature]:
264
+ path_features = [n for n in path if n != self.target_variable]
265
+ d = len(path_features)
266
+ m_values = defaultdict(float)
267
+ m_values[0] = 1.0
268
+
269
+ for node in path_features:
270
+ if node == feature:
271
+ continue
272
+
273
+ new_m_values = defaultdict(float)
274
+ for m, val in m_values.items():
275
+ new_m_values[m + 1] += val
276
+ new_m_values[m] += val
277
+ m_values = new_m_values
278
+
279
+ for m in m_values:
280
+ weight = shapley_weights.get((m, d), 0) * self.gamma.get(feature, 0)
281
+ delta_v = self._compute_path_delta_v(feature, path, m, x, is_classifier)
282
+ phi_causal[feature] += weight * delta_v
283
+
284
+ sum_phi = sum(phi_causal.values())
285
+ if sum_phi != 0:
286
+ scaling_factor = (f_x - E_fX) / sum_phi
287
+ phi_causal = {k: v * scaling_factor for k, v in phi_causal.items()}
288
+
289
+ return phi_causal
290
+
291
+ def _compute_path_delta_v(self, feature, path, m, x, is_classifier):
292
+ """Compute Δv for a causal path using precomputed expectations."""
293
+ S = [n for n in path[:m] if n != feature]
294
+ x_S = {n: x[n] for n in S if n in x}
295
+ v_S = self.compute_v_do(S, x_S, is_classifier)
296
+
297
+ S_with_i = S + [feature]
298
+ x_Si = {**x_S, feature: x[feature]}
299
+ v_Si = self.compute_v_do(S_with_i, x_Si, is_classifier)
300
+
301
+ return v_Si - v_S
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: fast-causal-shap
3
+ Version: 0.1.0
4
+ Summary: A Python package for efficient causal SHAP computations
5
+ Author-email: woonyee28 <ngnwy289@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/woonyee28/CausalSHAP
8
+ Project-URL: Issues, https://github.com/woonyee28/CausalSHAP/issues
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pandas>=1.0.0
13
+ Requires-Dist: networkx>=2.0
14
+ Requires-Dist: numpy>=1.18.0
15
+ Requires-Dist: scikit-learn>=0.24.0
16
+ Dynamic: license-file
17
+
18
+ # Fast Causal SHAP
19
+
20
+ This folder contains the core modules and components for the **Fast Causal SHAP** Python package. Fast Causal SHAP provides efficient and interpretable SHAP value computation for causal inference tasks.
21
+
22
+ ## Features
23
+
24
+ - Fast computation of SHAP values for causal models
25
+ - Support for multiple causal inference frameworks
26
+
27
+ ## Installation
28
+
29
+ Install Fast Causal SHAP using pip:
30
+
31
+ ```bash
32
+ pip install fast-causal-shap
33
+ ```
34
+
35
+ Or, for the latest development version:
36
+
37
+ ```bash
38
+ pip install git+https://github.com/woonyee28/CausalSHAP.git
39
+ ```
40
+
41
+ ## Usage
42
+ // To be added
43
+
44
+ ## Citation
45
+ If you use this package in your research, please cite:
46
+ // To be added
47
+
48
+ ## License
49
+
50
+ This project is licensed under the MIT License.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ fast_causal_shap/__init__.py
5
+ fast_causal_shap/core.py
6
+ fast_causal_shap.egg-info/PKG-INFO
7
+ fast_causal_shap.egg-info/SOURCES.txt
8
+ fast_causal_shap.egg-info/dependency_links.txt
9
+ fast_causal_shap.egg-info/requires.txt
10
+ fast_causal_shap.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ pandas>=1.0.0
2
+ networkx>=2.0
3
+ numpy>=1.18.0
4
+ scikit-learn>=0.24.0
@@ -0,0 +1 @@
1
+ fast_causal_shap
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "fast-causal-shap"
7
+ version = "0.1.0"
8
+ description = "A Python package for efficient causal SHAP computations"
9
+ readme = "README.md"
10
+ requires-python = ">=3.7"
11
+ license = {text = "MIT"}
12
+ authors = [
13
+ {name = "woonyee28", email = "ngnwy289@gmail.com"},
14
+ ]
15
+ dependencies = [
16
+ "pandas>=1.0.0",
17
+ "networkx>=2.0",
18
+ "numpy>=1.18.0",
19
+ "scikit-learn>=0.24.0",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/woonyee28/CausalSHAP"
24
+ Issues = "https://github.com/woonyee28/CausalSHAP/issues"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+