Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -89,22 +89,21 @@ def calculate_shap_values(model, x_tensor):
|
|
| 89 |
model.eval()
|
| 90 |
device = next(model.parameters()).device
|
| 91 |
|
| 92 |
-
# Create a background dataset (baseline) with a sufficient number of samples
|
| 93 |
-
background = np.zeros((300, x_tensor.shape[1]))
|
| 94 |
-
|
| 95 |
try:
|
| 96 |
-
#
|
|
|
|
|
|
|
|
|
|
| 97 |
explainer = shap.DeepExplainer(model, background)
|
| 98 |
-
# Calculate SHAP values using DeepExplainer
|
| 99 |
shap_values_all = explainer.shap_values(x_tensor)
|
|
|
|
| 100 |
# Get SHAP values for human class (index 1)
|
| 101 |
shap_values = shap_values_all[1][0]
|
| 102 |
except Exception as e:
|
| 103 |
print(f"DeepExplainer failed, falling back to KernelExplainer: {str(e)}")
|
| 104 |
|
| 105 |
-
# Define a wrapper
|
| 106 |
def model_predict(x):
|
| 107 |
-
# Ensure x is a numpy array and has at least 2 dimensions
|
| 108 |
if not isinstance(x, np.ndarray):
|
| 109 |
x = np.array(x)
|
| 110 |
if x.ndim == 1:
|
|
@@ -115,10 +114,9 @@ def calculate_shap_values(model, x_tensor):
|
|
| 115 |
probs = torch.softmax(output, dim=1)[:, 1] # Human probability
|
| 116 |
return probs.cpu().numpy()
|
| 117 |
|
| 118 |
-
#
|
| 119 |
background = np.zeros((300, x_tensor.shape[1]))
|
| 120 |
|
| 121 |
-
# Use KernelExplainer as fallback
|
| 122 |
explainer = shap.KernelExplainer(model_predict, background)
|
| 123 |
x_numpy = x_tensor.cpu().numpy()
|
| 124 |
shap_values = explainer.shap_values(x_numpy, nsamples=100)
|
|
|
|
| 89 |
model.eval()
|
| 90 |
device = next(model.parameters()).device
|
| 91 |
|
|
|
|
|
|
|
|
|
|
| 92 |
try:
|
| 93 |
+
# Create background as a torch tensor instead of a numpy array
|
| 94 |
+
background = torch.zeros((300, x_tensor.shape[1]), device=device)
|
| 95 |
+
|
| 96 |
+
# Use DeepExplainer with the torch tensor background
|
| 97 |
explainer = shap.DeepExplainer(model, background)
|
|
|
|
| 98 |
shap_values_all = explainer.shap_values(x_tensor)
|
| 99 |
+
|
| 100 |
# Get SHAP values for human class (index 1)
|
| 101 |
shap_values = shap_values_all[1][0]
|
| 102 |
except Exception as e:
|
| 103 |
print(f"DeepExplainer failed, falling back to KernelExplainer: {str(e)}")
|
| 104 |
|
| 105 |
+
# Define a wrapper that converts inputs to proper shape and tensor
|
| 106 |
def model_predict(x):
|
|
|
|
| 107 |
if not isinstance(x, np.ndarray):
|
| 108 |
x = np.array(x)
|
| 109 |
if x.ndim == 1:
|
|
|
|
| 114 |
probs = torch.softmax(output, dim=1)[:, 1] # Human probability
|
| 115 |
return probs.cpu().numpy()
|
| 116 |
|
| 117 |
+
# Use a numpy background for KernelExplainer
|
| 118 |
background = np.zeros((300, x_tensor.shape[1]))
|
| 119 |
|
|
|
|
| 120 |
explainer = shap.KernelExplainer(model_predict, background)
|
| 121 |
x_numpy = x_tensor.cpu().numpy()
|
| 122 |
shap_values = explainer.shap_values(x_numpy, nsamples=100)
|