Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -84,53 +84,97 @@ def sequence_to_kmer_vector(sequence: str, k: int = 4) -> np.ndarray:
|
|
84 |
###############################################################################
|
85 |
|
86 |
import shap
|
|
|
87 |
|
88 |
def calculate_shap_values(model, x_tensor):
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
model.eval()
|
90 |
device = next(model.parameters()).device
|
91 |
|
92 |
-
#
|
93 |
-
|
|
|
|
|
|
|
94 |
|
|
|
95 |
try:
|
96 |
-
#
|
97 |
-
|
98 |
-
|
99 |
-
|
|
|
|
|
|
|
100 |
shap_values_all = explainer.shap_values(x_tensor)
|
101 |
|
102 |
-
#
|
103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
except Exception as e:
|
106 |
-
print(f"
|
107 |
|
108 |
-
|
109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
with torch.no_grad():
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
shap_values = explainer.shap_values(x_numpy, nsamples=100)
|
125 |
-
|
126 |
-
# Get human probability
|
127 |
-
with torch.no_grad():
|
128 |
-
output = model(x_tensor)
|
129 |
-
probs = torch.softmax(output, dim=1)
|
130 |
-
prob_human = probs[0, 1].item()
|
131 |
-
|
132 |
-
return np.array(shap_values), prob_human
|
133 |
-
|
134 |
###############################################################################
|
135 |
# 4. PER-BASE SHAP AGGREGATION
|
136 |
###############################################################################
|
|
|
84 |
###############################################################################
|
85 |
|
86 |
import shap
|
87 |
+
from sklearn.linear_model import Ridge
|
88 |
|
89 |
def calculate_shap_values(model, x_tensor):
|
90 |
+
"""
|
91 |
+
Calculate SHAP values with three possible methods:
|
92 |
+
1. Try SHAP's GradientExplainer (better for deep models with unsupported layers)
|
93 |
+
2. Fall back to SHAP's KernelExplainer with fixed parameters if #1 fails
|
94 |
+
3. Fall back to original feature ablation method if both SHAP methods fail
|
95 |
+
"""
|
96 |
model.eval()
|
97 |
device = next(model.parameters()).device
|
98 |
|
99 |
+
# Get human probability for baseline
|
100 |
+
with torch.no_grad():
|
101 |
+
output = model(x_tensor)
|
102 |
+
probs = torch.softmax(output, dim=1)
|
103 |
+
prob_human = probs[0, 1].item()
|
104 |
|
105 |
+
# Try GradientExplainer first (better for neural nets with unsupported ops)
|
106 |
try:
|
107 |
+
# Create synthetic background data (more samples to avoid errors)
|
108 |
+
background = torch.zeros((20, x_tensor.shape[1]), device=device)
|
109 |
+
for i in range(20):
|
110 |
+
# Add small random noise to avoid singular matrices
|
111 |
+
background[i] = torch.randn_like(x_tensor[0]) * 0.01
|
112 |
+
|
113 |
+
explainer = shap.GradientExplainer(model, background)
|
114 |
shap_values_all = explainer.shap_values(x_tensor)
|
115 |
|
116 |
+
# For classification, shap_values is a list of arrays, one for each class
|
117 |
+
# We want the values for the "human" class (index 1)
|
118 |
+
if isinstance(shap_values_all, list) and len(shap_values_all) > 1:
|
119 |
+
shap_values = shap_values_all[1][0].cpu().numpy()
|
120 |
+
else:
|
121 |
+
shap_values = shap_values_all[0].cpu().numpy()
|
122 |
+
|
123 |
+
print("Using GradientExplainer for SHAP values")
|
124 |
+
return np.array(shap_values), prob_human
|
125 |
|
126 |
except Exception as e:
|
127 |
+
print(f"GradientExplainer failed: {str(e)}, trying KernelExplainer")
|
128 |
|
129 |
+
try:
|
130 |
+
# Create model wrapper function
|
131 |
+
def model_predict(x):
|
132 |
+
with torch.no_grad():
|
133 |
+
tensor_x = torch.FloatTensor(x).to(device)
|
134 |
+
output = model(tensor_x)
|
135 |
+
probs = torch.softmax(output, dim=1)[:, 1] # Human probability
|
136 |
+
return probs.cpu().numpy()
|
137 |
+
|
138 |
+
# Create more background samples (50 samples with random noise)
|
139 |
+
background = np.zeros((50, x_tensor.shape[1]))
|
140 |
+
for i in range(50):
|
141 |
+
# Small random values to create better background distribution
|
142 |
+
background[i] = np.random.normal(0, 0.01, x_tensor.shape[1])
|
143 |
+
|
144 |
+
# Force using Ridge regression instead of default LassoLarsIC
|
145 |
+
explainer = shap.KernelExplainer(
|
146 |
+
model_predict,
|
147 |
+
background,
|
148 |
+
link="identity", # Use raw output, not logit
|
149 |
+
l1_reg="num_features(10)", # Simplified regularization
|
150 |
+
model_regressor=Ridge(alpha=0.01) # Use Ridge instead of LassoLarsIC
|
151 |
+
)
|
152 |
+
|
153 |
+
# Calculate SHAP values with more samples
|
154 |
+
x_numpy = x_tensor.cpu().numpy()
|
155 |
+
shap_values = explainer.shap_values(x_numpy, nsamples=300)
|
156 |
+
|
157 |
+
print("Using KernelExplainer for SHAP values")
|
158 |
+
return np.array(shap_values), prob_human
|
159 |
+
|
160 |
+
except Exception as e:
|
161 |
+
print(f"KernelExplainer failed: {str(e)}, falling back to ablation method")
|
162 |
+
|
163 |
+
# Fall back to original feature ablation method
|
164 |
with torch.no_grad():
|
165 |
+
shap_values = []
|
166 |
+
x_zeroed = x_tensor.clone()
|
167 |
+
for i in range(x_tensor.shape[1]):
|
168 |
+
original_val = x_zeroed[0, i].item()
|
169 |
+
x_zeroed[0, i] = 0.0
|
170 |
+
output = model(x_zeroed)
|
171 |
+
probs = torch.softmax(output, dim=1)
|
172 |
+
prob = probs[0, 1].item()
|
173 |
+
shap_values.append(prob_human - prob)
|
174 |
+
x_zeroed[0, i] = original_val
|
175 |
+
|
176 |
+
print("Using ablation method for SHAP values")
|
177 |
+
return np.array(shap_values), prob_human
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
###############################################################################
|
179 |
# 4. PER-BASE SHAP AGGREGATION
|
180 |
###############################################################################
|