Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,269 +8,142 @@ import torch
|
|
| 8 |
from transformers import BertTokenizer, BertModel
|
| 9 |
from lime.lime_tabular import LimeTabularExplainer
|
| 10 |
from math import expm1
|
| 11 |
-
import matplotlib.pyplot as plt
|
| 12 |
-
import io
|
| 13 |
-
import base64
|
| 14 |
-
import os
|
| 15 |
|
| 16 |
-
|
| 17 |
-
MODEL_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
model = joblib.load(os.path.join(MODEL_DIR, "RF.joblib"))
|
| 22 |
-
scaler = joblib.load(os.path.join(MODEL_DIR, "norm (4).joblib"))
|
| 23 |
-
except FileNotFoundError as e:
|
| 24 |
-
raise gr.Error(f"Classifier model or scaler not found: {e}. Make sure RF.joblib and norm (4).joblib are in the {MODEL_DIR} directory.")
|
| 25 |
-
except Exception as e:
|
| 26 |
-
raise gr.Error(f"Error loading classifier components: {e}")
|
| 27 |
|
| 28 |
-
|
| 29 |
-
try:
|
| 30 |
-
tokenizer = BertTokenizer.from_pretrained("Rostlab/prot_bert", do_lower_case=False)
|
| 31 |
-
protbert_model = BertModel.from_pretrained("Rostlab/prot_bert")
|
| 32 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 33 |
-
protbert_model = protbert_model.to(device).eval()
|
| 34 |
-
except Exception as e:
|
| 35 |
-
raise gr.Error(f"Error loading ProtBert model/tokenizer: {e}. Check internet connection or model availability.")
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
| 39 |
-
selected_features = ["_SolventAccessibilityC3", "_SecondaryStrC1", "_SecondaryStrC3", "_ChargeC1", "_PolarityC1",
|
| 40 |
-
"_NormalizedVDWVC1", "_HydrophobicityC3", "_SecondaryStrT23", "_PolarizabilityD1001", "_PolarizabilityD2001",
|
| 41 |
-
"_PolarabilityD3001", "_SolventAccessibilityD1001", "_SolventAccessibilityD2001", "_SolventAccessibilityD3001",
|
| 42 |
-
"_SecondaryStrD1001", "_SecondaryStrD1075", "_SecondaryStrD2001", "_SecondaryStrD3001", "_ChargeD1001",
|
| 43 |
-
"_ChargeD1025", "_ChargeD2001", "_ChargeD3075", "_ChargeD3100", "_PolarityD1001", "_PolarityD1050",
|
| 44 |
-
"_PolarityD2001", "_PolarityD3001", "_NormalizedVDWVD1001", "_NormalizedVDWVD2001", "_NormalizedVDWVD2025",
|
| 45 |
-
"_NormalizedVDWVD2050", "_NormalizedVDWVD3001", "_HydrophobicityD1001", "_HydrophobicityD2001",
|
| 46 |
-
"_HydrophobicityD3001", "_HydrophobicityD3025", "A", "R", "D", "C", "E", "Q", "H", "I", "M", "P", "Y", "V",
|
| 47 |
-
"AR", "AV", "RC", "RL", "RV", "CR", "CC", "CL", "CK", "EE", "EI", "EL", "HC", "IA", "IL", "IV", "LA", "LC", "LE",
|
| 48 |
-
"LI", "LT", "LV", "KC", "MA", "MS", "SC", "TC", "TV", "YC", "VC", "VE", "VL", "VK", "VV",
|
| 49 |
-
"MoreauBrotoAuto_FreeEnergy30", "MoranAuto_Hydrophobicity2", "MoranAuto_Hydrophobicity4",
|
| 50 |
-
"GearyAuto_Hydrophobicity20", "GearyAuto_Hydrophobicity24", "GearyAuto_Hydrophobicity26",
|
| 51 |
-
"GearyAuto_Hydrophobicity27", "GearyAuto_Hydrophobicity28", "GearyAuto_Hydrophobicity29",
|
| 52 |
-
"GearyAuto_Hydrophobicity30", "GearyAuto_AvFlexibility22", "GearyAuto_AvFlexibility26",
|
| 53 |
-
"GearyAuto_AvFlexibility27", "GearyAuto_AvFlexibility28", "GearyAuto_AvFlexibility29", "GearyAuto_AvFlexibility30",
|
| 54 |
-
"GearyAuto_Polarizability22", "GearyAuto_Polarizability24", "GearyAuto_Polarizability25",
|
| 55 |
-
"GearyAuto_Polarizability27", "GearyAuto_Polarizability28", "GearyAuto_Polarizability29",
|
| 56 |
-
"GearyAuto_Polarizability30", "GearyAuto_FreeEnergy24", "GearyAuto_FreeEnergy25", "GearyAuto_FreeEnergy30",
|
| 57 |
-
"GearyAuto_ResidueASA21", "GearyAuto_ResidueASA22", "GearyAuto_ResidueASA23", "GearyAuto_ResidueASA24",
|
| 58 |
-
"GearyAuto_ResidueASA30", "GearyAuto_ResidueVol21", "GearyAuto_ResidueVol24", "GearyAuto_ResidueVol25",
|
| 59 |
-
"GearyAuto_ResidueVol26", "GearyAuto_ResidueVol28", "GearyAuto_ResidueVol29", "GearyAuto_ResidueVol30",
|
| 60 |
-
"GearyAuto_Steric18", "GearyAuto_Steric21", "GearyAuto_Steric26", "GearyAuto_Steric27", "GearyAuto_Steric28",
|
| 61 |
-
"GearyAuto_Steric29", "GearyAuto_Steric30", "GearyAuto_Mutability23", "GearyAuto_Mutability25",
|
| 62 |
-
"GearyAuto_Mutability26", "GearyAuto_Mutability27", "GearyAuto_Mutability28", "GearyAuto_Mutability29",
|
| 63 |
-
"GearyAuto_Mutability30", "APAAC1", "APAAC4", "APAAC5", "APAAC6", "APAAC8", "APAAC9", "APAAC12", "APAAC13",
|
| 64 |
-
"APAAC15", "APAAC18", "APAAC19", "APAAC24"]
|
| 65 |
-
|
| 66 |
-
# LIME Explainer Setup
|
| 67 |
-
try:
|
| 68 |
-
sample_data = np.random.rand(500, len(selected_features)) # Fallback: Generate random sample data
|
| 69 |
-
except Exception:
|
| 70 |
-
print("Warning: Could not load pre-saved sample data for LIME. Generating random sample data.")
|
| 71 |
-
sample_data = np.random.rand(500, len(selected_features))
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
explainer = LimeTabularExplainer(
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
)
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
weights = [item[1] for item in explanation_list]
|
| 166 |
-
|
| 167 |
-
sorted_indices = np.argsort(np.abs(weights))[::-1]
|
| 168 |
-
features_sorted = [features[i] for i in sorted_indices]
|
| 169 |
-
weights_sorted = [weights[i] for i in sorted_indices]
|
| 170 |
-
|
| 171 |
-
y_pos = np.arange(len(features_sorted))
|
| 172 |
-
colors = ['green' if w > 0 else 'red' for w in weights_sorted]
|
| 173 |
-
ax.barh(y_pos, weights_sorted, align='center', color=colors)
|
| 174 |
-
ax.set_yticks(y_pos)
|
| 175 |
-
ax.set_yticklabels(features_sorted, fontsize=10)
|
| 176 |
-
ax.invert_yaxis()
|
| 177 |
-
ax.set_xlabel('Contribution to Prediction (LIME Weight)', fontsize=12)
|
| 178 |
-
ax.set_title('Top Features Influencing Prediction (LIME)', fontsize=14)
|
| 179 |
-
ax.axvline(0, color='grey', linestyle='--', linewidth=0.8)
|
| 180 |
-
plt.grid(axis='x', linestyle=':', alpha=0.7)
|
| 181 |
-
|
| 182 |
-
buf = io.BytesIO()
|
| 183 |
-
plt.savefig(buf, format='png', bbox_inches='tight', dpi=150)
|
| 184 |
-
buf.seek(0)
|
| 185 |
-
image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
|
| 186 |
-
plt.close(fig)
|
| 187 |
-
return image_base64
|
| 188 |
-
|
| 189 |
-
# --- Gradio API Endpoints ---
|
| 190 |
-
|
| 191 |
-
def classify_and_interpret_amp(sequence: str) -> dict:
|
| 192 |
-
try:
|
| 193 |
-
features = extract_features(sequence)
|
| 194 |
-
|
| 195 |
-
prediction_class_idx = model.predict(features)[0]
|
| 196 |
-
probabilities = model.predict_proba(features)[0]
|
| 197 |
-
|
| 198 |
-
amp_label = "AMP (Positive)" if prediction_class_idx == 0 else "Non-AMP"
|
| 199 |
-
confidence = probabilities[prediction_class_idx]
|
| 200 |
-
|
| 201 |
-
explanation = explainer.explain_instance(
|
| 202 |
-
data_row=features[0],
|
| 203 |
-
predict_fn=model.predict_proba,
|
| 204 |
-
num_features=10
|
| 205 |
-
)
|
| 206 |
-
|
| 207 |
-
top_features = []
|
| 208 |
-
for feat_str, weight in explanation.as_list():
|
| 209 |
-
parts = feat_str.split(" ", 1)
|
| 210 |
-
feature_name = parts[0]
|
| 211 |
-
condition = parts[1] if len(parts) > 1 else ""
|
| 212 |
-
|
| 213 |
-
top_features.append({
|
| 214 |
-
"feature": feature_name,
|
| 215 |
-
"condition": condition.strip(),
|
| 216 |
-
"value": round(weight, 4)
|
| 217 |
-
})
|
| 218 |
-
|
| 219 |
-
lime_plot_base64_str = generate_lime_plot_base64(explanation.as_list())
|
| 220 |
-
|
| 221 |
-
return {
|
| 222 |
-
"label": amp_label,
|
| 223 |
-
"confidence": float(confidence),
|
| 224 |
-
"shap_plot_base64": lime_plot_base64_str,
|
| 225 |
-
"top_features": top_features
|
| 226 |
-
}
|
| 227 |
-
|
| 228 |
-
except gr.Error as e:
|
| 229 |
-
raise e
|
| 230 |
-
except Exception as e:
|
| 231 |
-
raise gr.Error(f"An unexpected error occurred during AMP classification: {e}")
|
| 232 |
-
|
| 233 |
-
def get_mic_predictions_api(sequence: str, selected_bacteria_keys: list) -> dict:
|
| 234 |
-
try:
|
| 235 |
-
mic_results = predictmic(sequence, selected_bacteria_keys)
|
| 236 |
-
return mic_results
|
| 237 |
-
except gr.Error as e:
|
| 238 |
-
raise e
|
| 239 |
-
except Exception as e:
|
| 240 |
-
raise gr.Error(f"An unexpected error occurred during MIC prediction API call: {e}")
|
| 241 |
-
|
| 242 |
-
# --- Gradio Interface Definition ---
|
| 243 |
-
with gr.Blocks() as demo:
|
| 244 |
-
gr.Markdown("# EPIC-AMP Platform Backend API")
|
| 245 |
-
gr.Markdown("This Gradio application provides the backend services for the EPIC-AMP frontend.")
|
| 246 |
-
|
| 247 |
-
with gr.Tab("AMP Classification & Interpretability API"):
|
| 248 |
-
gr.Markdown("### `/predict` Endpoint (AMP Classification, Confidence, LIME Plot, Top Features)")
|
| 249 |
-
gr.Markdown("Input an amino acid sequence (10-100 AAs) to get classification details.")
|
| 250 |
-
sequence_input_amp = gr.Textbox(label="Amino Acid Sequence", lines=5, placeholder="Enter sequence here...")
|
| 251 |
-
amp_api_output = gr.Json(label="AMP Prediction Details JSON Output")
|
| 252 |
-
gr.Button("Test Classification").click(
|
| 253 |
-
fn=classify_and_interpret_amp,
|
| 254 |
-
inputs=[sequence_input_amp],
|
| 255 |
-
outputs=[amp_api_output],
|
| 256 |
-
api_name="predict"
|
| 257 |
-
)
|
| 258 |
-
|
| 259 |
-
with gr.Tab("MIC Prediction API"):
|
| 260 |
-
gr.Markdown("### `/predict_mic` Endpoint (MIC Values)")
|
| 261 |
-
gr.Markdown("Input an amino acid sequence (only if classified as AMP) and select bacteria to get predicted MIC values.")
|
| 262 |
-
sequence_input_mic = gr.Textbox(label="Amino Acid Sequence", lines=5, placeholder="Enter AMP sequence for MIC prediction...")
|
| 263 |
-
mic_bacteria_checkboxes = gr.CheckboxGroup(
|
| 264 |
-
choices=["e_coli", "p_aeruginosa", "s_aureus", "k_pneumoniae"],
|
| 265 |
-
label="Select Bacteria for MIC Prediction (keys for backend)"
|
| 266 |
-
)
|
| 267 |
-
mic_api_output = gr.Json(label="MIC Prediction JSON Output")
|
| 268 |
-
gr.Button("Test MIC Prediction").click(
|
| 269 |
-
fn=get_mic_predictions_api,
|
| 270 |
-
inputs=[sequence_input_mic, mic_bacteria_checkboxes],
|
| 271 |
-
outputs=[mic_api_output],
|
| 272 |
-
api_name="predict_mic"
|
| 273 |
-
)
|
| 274 |
|
| 275 |
-
|
| 276 |
-
demo.launch(share=True, show_api=True)
|
|
|
|
| 8 |
from transformers import BertTokenizer, BertModel
|
| 9 |
from lime.lime_tabular import LimeTabularExplainer
|
| 10 |
from math import expm1
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
Load AMP Classifier
|
|
|
|
| 13 |
|
| 14 |
+
model = joblib.load("RF.joblib")
|
| 15 |
+
scaler = joblib.load("norm (4).joblib")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
Load ProtBert
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
tokenizer = BertTokenizer.from_pretrained("Rostlab/prot_bert", do_lower_case=False)
|
| 20 |
+
protbert_model = BertModel.from_pretrained("Rostlab/prot_bert")
|
| 21 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 22 |
+
protbert_model = protbert_model.to(device).eval()
|
| 23 |
|
| 24 |
+
Full list of selected features
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
selected_features = ["_SolventAccessibilityC3", "_SecondaryStrC1", "_SecondaryStrC3", "_ChargeC1", "_PolarityC1",
|
| 27 |
+
"_NormalizedVDWVC1", "_HydrophobicityC3", "_SecondaryStrT23", "_PolarizabilityD1001", "_PolarizabilityD2001",
|
| 28 |
+
"_PolarizabilityD3001", "_SolventAccessibilityD1001", "_SolventAccessibilityD2001", "_SolventAccessibilityD3001",
|
| 29 |
+
"_SecondaryStrD1001", "_SecondaryStrD1075", "_SecondaryStrD2001", "_SecondaryStrD3001", "_ChargeD1001",
|
| 30 |
+
"_ChargeD1025", "_ChargeD2001", "_ChargeD3075", "_ChargeD3100", "_PolarityD1001", "_PolarityD1050",
|
| 31 |
+
"_PolarityD2001", "_PolarityD3001", "_NormalizedVDWVD1001", "_NormalizedVDWVD2001", "_NormalizedVDWVD2025",
|
| 32 |
+
"_NormalizedVDWVD2050", "_NormalizedVDWVD3001", "_HydrophobicityD1001", "_HydrophobicityD2001",
|
| 33 |
+
"_HydrophobicityD3001", "_HydrophobicityD3025", "A", "R", "D", "C", "E", "Q", "H", "I", "M", "P", "Y", "V",
|
| 34 |
+
"AR", "AV", "RC", "RL", "RV", "CR", "CC", "CL", "CK", "EE", "EI", "EL", "HC", "IA", "IL", "IV", "LA", "LC", "LE",
|
| 35 |
+
"LI", "LT", "LV", "KC", "MA", "MS", "SC", "TC", "TV", "YC", "VC", "VE", "VL", "VK", "VV",
|
| 36 |
+
"MoreauBrotoAuto_FreeEnergy30", "MoranAuto_Hydrophobicity2", "MoranAuto_Hydrophobicity4",
|
| 37 |
+
"GearyAuto_Hydrophobicity20", "GearyAuto_Hydrophobicity24", "GearyAuto_Hydrophobicity26",
|
| 38 |
+
"GearyAuto_Hydrophobicity27", "GearyAuto_Hydrophobicity28", "GearyAuto_Hydrophobicity29",
|
| 39 |
+
"GearyAuto_Hydrophobicity30", "GearyAuto_AvFlexibility22", "GearyAuto_AvFlexibility26",
|
| 40 |
+
"GearyAuto_AvFlexibility27", "GearyAuto_AvFlexibility28", "GearyAuto_AvFlexibility29", "GearyAuto_AvFlexibility30",
|
| 41 |
+
"GearyAuto_Polarizability22", "GearyAuto_Polarizability24", "GearyAuto_Polarizability25",
|
| 42 |
+
"GearyAuto_Polarizability27", "GearyAuto_Polarizability28", "GearyAuto_Polarizability29",
|
| 43 |
+
"GearyAuto_Polarizability30", "GearyAuto_FreeEnergy24", "GearyAuto_FreeEnergy25", "GearyAuto_FreeEnergy30",
|
| 44 |
+
"GearyAuto_ResidueASA21", "GearyAuto_ResidueASA22", "GearyAuto_ResidueASA23", "GearyAuto_ResidueASA24",
|
| 45 |
+
"GearyAuto_ResidueASA30", "GearyAuto_ResidueVol21", "GearyAuto_ResidueVol24", "GearyAuto_ResidueVol25",
|
| 46 |
+
"GearyAuto_ResidueVol26", "GearyAuto_ResidueVol28", "GearyAuto_ResidueVol29", "GearyAuto_ResidueVol30",
|
| 47 |
+
"GearyAuto_Steric18", "GearyAuto_Steric21", "GearyAuto_Steric26", "GearyAuto_Steric27", "GearyAuto_Steric28",
|
| 48 |
+
"GearyAuto_Steric29", "GearyAuto_Steric30", "GearyAuto_Mutability23", "GearyAuto_Mutability25",
|
| 49 |
+
"GearyAuto_Mutability26", "GearyAuto_Mutability27", "GearyAuto_Mutability28", "GearyAuto_Mutability29",
|
| 50 |
+
"GearyAuto_Mutability30", "APAAC1", "APAAC4", "APAAC5", "APAAC6", "APAAC8", "APAAC9", "APAAC12", "APAAC13",
|
| 51 |
+
"APAAC15", "APAAC18", "APAAC19", "APAAC24"]
|
| 52 |
+
|
| 53 |
+
LIME Explainer Setup
|
| 54 |
+
|
| 55 |
+
sample_data = np.random.rand(100, len(selected_features))
|
| 56 |
explainer = LimeTabularExplainer(
|
| 57 |
+
training_data=sample_data,
|
| 58 |
+
feature_names=selected_features,
|
| 59 |
+
class_names=["AMP", "Non-AMP"],
|
| 60 |
+
mode="classification"
|
| 61 |
)
|
| 62 |
|
| 63 |
+
def extract_features(sequence):
|
| 64 |
+
sequence = ''.join([aa for aa in sequence.upper() if aa in "ACDEFGHIKLMNPQRSTVWY"])
|
| 65 |
+
if len(sequence) < 10:
|
| 66 |
+
return "Error: Sequence too short."
|
| 67 |
+
dipeptide_features = AAComposition.CalculateAADipeptideComposition(sequence)
|
| 68 |
+
filtered_dipeptide_features = {k: dipeptide_features[k] for k in list(dipeptide_features.keys())[:420]}
|
| 69 |
+
ctd_features = CTD.CalculateCTD(sequence)
|
| 70 |
+
auto_features = Autocorrelation.CalculateAutoTotal(sequence)
|
| 71 |
+
pseudo_features = PseudoAAC.GetAPseudoAAC(sequence, lamda=9)
|
| 72 |
+
all_features_dict = {}
|
| 73 |
+
all_features_dict.update(ctd_features)
|
| 74 |
+
all_features_dict.update(filtered_dipeptide_features)
|
| 75 |
+
all_features_dict.update(auto_features)
|
| 76 |
+
all_features_dict.update(pseudo_features)
|
| 77 |
+
feature_df_all = pd.DataFrame([all_features_dict])
|
| 78 |
+
normalized_array = scaler.transform(feature_df_all.values)
|
| 79 |
+
normalized_df = pd.DataFrame(normalized_array, columns=feature_df_all.columns)
|
| 80 |
+
if not set(selected_features).issubset(set(normalized_df.columns)):
|
| 81 |
+
return "Error: Some selected features are missing from computed features."
|
| 82 |
+
selected_df = normalized_df[selected_features].fillna(0)
|
| 83 |
+
return selected_df.values
|
| 84 |
+
|
| 85 |
+
def predictmic(sequence):
|
| 86 |
+
sequence = ''.join([aa for aa in sequence.upper() if aa in "ACDEFGHIKLMNPQRSTVWY"])
|
| 87 |
+
if len(sequence) < 10:
|
| 88 |
+
return {"Error": "Sequence too short or invalid."}
|
| 89 |
+
seq_spaced = ' '.join(list(sequence))
|
| 90 |
+
tokens = tokenizer(seq_spaced, return_tensors="pt", padding='max_length', truncation=True, max_length=512)
|
| 91 |
+
tokens = {k: v.to(device) for k, v in tokens.items()}
|
| 92 |
+
with torch.no_grad():
|
| 93 |
+
outputs = protbert_model(**tokens)
|
| 94 |
+
embedding = outputs.last_hidden_state.mean(dim=1).squeeze().cpu().numpy().reshape(1, -1)
|
| 95 |
+
bacteria_config = {
|
| 96 |
+
"E.coli": {"model": "coli_xgboost_model.pkl", "scaler": "coli_scaler.pkl", "pca": None},
|
| 97 |
+
"S.aureus": {"model": "aur_xgboost_model.pkl", "scaler": "aur_scaler.pkl", "pca": None},
|
| 98 |
+
"P.aeruginosa": {"model": "arg_xgboost_model.pkl", "scaler": "arg_scaler.pkl", "pca": None},
|
| 99 |
+
"K.Pneumonia": {"model": "pne_mlp_model.pkl", "scaler": "pne_scaler.pkl", "pca": "pne_pca.pkl"}
|
| 100 |
+
}
|
| 101 |
+
mic_results = {}
|
| 102 |
+
for bacterium, cfg in bacteria_config.items():
|
| 103 |
+
try:
|
| 104 |
+
scaler = joblib.load(cfg["scaler"])
|
| 105 |
+
scaled = scaler.transform(embedding)
|
| 106 |
+
transformed = joblib.load(cfg["pca"]).transform(scaled) if cfg["pca"] else scaled
|
| 107 |
+
model = joblib.load(cfg["model"])
|
| 108 |
+
mic_log = model.predict(transformed)[0]
|
| 109 |
+
mic = round(expm1(mic_log), 3)
|
| 110 |
+
mic_results[bacterium] = mic
|
| 111 |
+
except Exception as e:
|
| 112 |
+
mic_results[bacterium] = f"Error: {str(e)}"
|
| 113 |
+
return mic_results
|
| 114 |
+
|
| 115 |
+
def full_prediction(sequence):
|
| 116 |
+
features = extract_features(sequence)
|
| 117 |
+
if isinstance(features, str):
|
| 118 |
+
return features
|
| 119 |
+
prediction = model.predict(features)[0]
|
| 120 |
+
probabilities = model.predict_proba(features)[0]
|
| 121 |
+
amp_result = "Antimicrobial Peptide (AMP)" if prediction == 0 else "Non-AMP"
|
| 122 |
+
confidence = round(probabilities[0 if prediction == 0 else 1] * 100, 2)
|
| 123 |
+
result = f"Prediction: {amp_result}\nConfidence: {confidence}%\n"
|
| 124 |
+
if prediction == 0:
|
| 125 |
+
mic_values = predictmic(sequence)
|
| 126 |
+
result += "\nPredicted MIC Values (\u00b5M):\n"
|
| 127 |
+
for org, mic in mic_values.items():
|
| 128 |
+
result += f"- {org}: {mic}\n"
|
| 129 |
+
else:
|
| 130 |
+
result += "\nMIC prediction skipped for Non-AMP sequences.\n"
|
| 131 |
+
explanation = explainer.explain_instance(
|
| 132 |
+
data_row=features[0],
|
| 133 |
+
predict_fn=model.predict_proba,
|
| 134 |
+
num_features=10
|
| 135 |
+
)
|
| 136 |
+
result += "\nTop Features Influencing Prediction:\n"
|
| 137 |
+
for feat, weight in explanation.as_list():
|
| 138 |
+
result += f"- {feat}: {round(weight, 4)}\n"
|
| 139 |
+
return result
|
| 140 |
+
|
| 141 |
+
iface = gr.Interface(
|
| 142 |
+
fn=full_prediction,
|
| 143 |
+
inputs=gr.Textbox(label="Enter Protein Sequence"),
|
| 144 |
+
outputs=gr.Textbox(label="Results"),
|
| 145 |
+
title="AMP & MIC Predictor + LIME Explanation",
|
| 146 |
+
description="Paste an amino acid sequence (\u226510 characters). Get AMP classification, MIC predictions, and LIME interpretability insights."
|
| 147 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
+
iface.launch(share=True)
|
|
|