Spaces:
Running
Running
Upload explain/shap_wrapper.py with huggingface_hub
Browse files- explain/shap_wrapper.py +32 -0
explain/shap_wrapper.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class GNNFeatureWrapper:
|
| 6 |
+
def __init__(self, model, data_obj, target_task_idx: int, device: str):
|
| 7 |
+
self.model = model.to(device)
|
| 8 |
+
self.data_obj = data_obj
|
| 9 |
+
self.target_task_idx = target_task_idx
|
| 10 |
+
self.device = device
|
| 11 |
+
self.model.eval()
|
| 12 |
+
|
| 13 |
+
def __call__(self, binary_coalitions: np.ndarray) -> np.ndarray:
|
| 14 |
+
predictions = []
|
| 15 |
+
with torch.no_grad():
|
| 16 |
+
for coalition in binary_coalitions:
|
| 17 |
+
x_perturbed = self.data_obj.x.clone().to(self.device)
|
| 18 |
+
mask_tensor = torch.tensor(
|
| 19 |
+
coalition, dtype=torch.float32, device=self.device
|
| 20 |
+
).unsqueeze(1)
|
| 21 |
+
x_perturbed = x_perturbed * mask_tensor
|
| 22 |
+
|
| 23 |
+
logits = self.model(
|
| 24 |
+
x_perturbed,
|
| 25 |
+
self.data_obj.edge_index.to(self.device),
|
| 26 |
+
self.data_obj.edge_attr.to(self.device),
|
| 27 |
+
torch.zeros(x_perturbed.shape[0], dtype=torch.long, device=self.device),
|
| 28 |
+
)
|
| 29 |
+
probs = torch.sigmoid(logits)
|
| 30 |
+
predictions.append(probs[0, self.target_task_idx].cpu().item())
|
| 31 |
+
|
| 32 |
+
return np.array(predictions)
|