Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,92 +2,136 @@ import gradio as gr
|
|
| 2 |
import joblib
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
-
from propy import AAComposition,
|
| 6 |
-
|
|
|
|
| 7 |
import torch
|
| 8 |
from transformers import BertTokenizer, BertModel
|
| 9 |
from lime.lime_tabular import LimeTabularExplainer
|
| 10 |
from math import expm1
|
| 11 |
|
| 12 |
-
# Load AMP Classifier and Scaler
|
| 13 |
-
model =
|
| 14 |
-
scaler = joblib.load("
|
| 15 |
|
| 16 |
-
# Load ProtBert
|
| 17 |
tokenizer = BertTokenizer.from_pretrained("Rostlab/prot_bert", do_lower_case=False)
|
| 18 |
protbert_model = BertModel.from_pretrained("Rostlab/prot_bert")
|
| 19 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 20 |
protbert_model = protbert_model.to(device).eval()
|
| 21 |
|
| 22 |
-
# Define selected features (
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
# Dummy data for LIME
|
| 51 |
sample_data = np.random.rand(100, len(selected_features))
|
| 52 |
explainer = LimeTabularExplainer(
|
| 53 |
training_data=sample_data,
|
| 54 |
feature_names=selected_features,
|
| 55 |
-
class_names=["AMP", "
|
| 56 |
mode="classification"
|
| 57 |
)
|
| 58 |
|
| 59 |
-
# Feature extraction function
|
| 60 |
def extract_features(sequence):
|
| 61 |
sequence = ''.join([aa for aa in sequence.upper() if aa in "ACDEFGHIKLMNPQRSTVWY"])
|
| 62 |
if len(sequence) < 10:
|
| 63 |
return "Error: Sequence too short."
|
| 64 |
|
| 65 |
try:
|
|
|
|
| 66 |
dipeptide_features = AAComposition.CalculateAADipeptideComposition(sequence)
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
ctd_features = CTD.CalculateCTD(sequence)
|
| 69 |
-
auto_features = Autocorrelation.CalculateAutoTotal(sequence)
|
| 70 |
-
pseudo_features = PseudoAAC.GetAPseudoAAC(sequence, lamda=9)
|
| 71 |
|
| 72 |
all_features_dict = {}
|
| 73 |
all_features_dict.update(ctd_features)
|
| 74 |
-
all_features_dict.update(
|
| 75 |
-
all_features_dict.update(auto_features)
|
| 76 |
-
all_features_dict.update(pseudo_features)
|
| 77 |
|
| 78 |
feature_df_all = pd.DataFrame([all_features_dict])
|
| 79 |
normalized_array = scaler.transform(feature_df_all.values)
|
| 80 |
normalized_df = pd.DataFrame(normalized_array, columns=feature_df_all.columns)
|
| 81 |
|
| 82 |
if not set(selected_features).issubset(normalized_df.columns):
|
| 83 |
-
|
|
|
|
| 84 |
|
| 85 |
selected_df = normalized_df[selected_features].fillna(0)
|
| 86 |
-
return selected_df.values
|
| 87 |
except Exception as e:
|
| 88 |
return f"Error in feature extraction: {str(e)}"
|
| 89 |
|
| 90 |
-
# MIC prediction function
|
| 91 |
def predictmic(sequence):
|
| 92 |
sequence = ''.join([aa for aa in sequence.upper() if aa in "ACDEFGHIKLMNPQRSTVWY"])
|
| 93 |
if len(sequence) < 10:
|
|
@@ -111,11 +155,11 @@ def predictmic(sequence):
|
|
| 111 |
mic_results = {}
|
| 112 |
for bacterium, cfg in bacteria_config.items():
|
| 113 |
try:
|
| 114 |
-
|
| 115 |
-
scaled =
|
| 116 |
transformed = joblib.load(cfg["pca"]).transform(scaled) if cfg["pca"] else scaled
|
| 117 |
-
|
| 118 |
-
mic_log =
|
| 119 |
mic = round(expm1(mic_log), 3)
|
| 120 |
mic_results[bacterium] = mic
|
| 121 |
except Exception as e:
|
|
@@ -129,19 +173,28 @@ def full_prediction(sequence):
|
|
| 129 |
if isinstance(features, str):
|
| 130 |
return features
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
-
|
|
|
|
| 142 |
result = f"Prediction: {amp_result}\nConfidence: {confidence}%\n"
|
| 143 |
|
| 144 |
-
if prediction ==
|
| 145 |
mic_values = predictmic(sequence)
|
| 146 |
result += "\nPredicted MIC Values (μM):\n"
|
| 147 |
for org, mic in mic_values.items():
|
|
@@ -149,15 +202,19 @@ def full_prediction(sequence):
|
|
| 149 |
else:
|
| 150 |
result += "\nMIC prediction skipped for Non-AMP sequences.\n"
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
result +=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
return result
|
| 163 |
|
|
@@ -170,4 +227,4 @@ iface = gr.Interface(
|
|
| 170 |
description="Paste an amino acid sequence (≥10 characters). Get AMP classification, MIC predictions, and LIME interpretability insights."
|
| 171 |
)
|
| 172 |
|
| 173 |
-
iface.launch(share=True)
|
|
|
|
| 2 |
import joblib
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
+
from propy import AAComposition, CTD
|
| 6 |
+
import tensorflow as tf
|
| 7 |
+
from tensorflow.keras.models import load_model
|
| 8 |
import torch
|
| 9 |
from transformers import BertTokenizer, BertModel
|
| 10 |
from lime.lime_tabular import LimeTabularExplainer
|
| 11 |
from math import expm1
|
| 12 |
|
| 13 |
+
# Load AMP Classifier (Keras) and Scaler
|
| 14 |
+
model = load_model("Comb1_aac_ctd_RFE_selected_features_model.keras")
|
| 15 |
+
scaler = joblib.load("Comb1_aac_ctd_RFE_selected_features_scaler.joblib")
|
| 16 |
|
| 17 |
+
# Load ProtBert (for MIC prediction)
|
| 18 |
tokenizer = BertTokenizer.from_pretrained("Rostlab/prot_bert", do_lower_case=False)
|
| 19 |
protbert_model = BertModel.from_pretrained("Rostlab/prot_bert")
|
| 20 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 21 |
protbert_model = protbert_model.to(device).eval()
|
| 22 |
|
| 23 |
+
# Define selected features (AAC + CTD, RFE-selected)
|
| 24 |
+
# Note: 'Activity' is the target label and is excluded from input features
|
| 25 |
+
selected_features = [
|
| 26 |
+
'_PolarizabilityC1', '_PolarizabilityC2', '_PolarizabilityC3',
|
| 27 |
+
'_SolventAccessibilityC1', '_SolventAccessibilityC2', '_SolventAccessibilityC3',
|
| 28 |
+
'_SecondaryStrC1', '_SecondaryStrC2', '_SecondaryStrC3',
|
| 29 |
+
'_ChargeC1', '_ChargeC2', '_ChargeC3',
|
| 30 |
+
'_PolarityC1', '_PolarityC2', '_PolarityC3',
|
| 31 |
+
'_NormalizedVDWVC1', '_NormalizedVDWVC2', '_NormalizedVDWVC3',
|
| 32 |
+
'_HydrophobicityC1', '_HydrophobicityC2', '_HydrophobicityC3',
|
| 33 |
+
'_PolarizabilityT12', '_PolarizabilityT13', '_PolarizabilityT23',
|
| 34 |
+
'_SolventAccessibilityT12', '_SolventAccessibilityT13', '_SolventAccessibilityT23',
|
| 35 |
+
'_SecondaryStrT12', '_SecondaryStrT13', '_SecondaryStrT23',
|
| 36 |
+
'_ChargeT12', '_ChargeT13', '_ChargeT23',
|
| 37 |
+
'_PolarityT12', '_PolarityT13', '_PolarityT23',
|
| 38 |
+
'_NormalizedVDWVT12', '_NormalizedVDWVT13', '_NormalizedVDWVT23',
|
| 39 |
+
'_HydrophobicityT12', '_HydrophobicityT13', '_HydrophobicityT23',
|
| 40 |
+
'A', 'R', 'N', 'D', 'C', 'E', 'Q', 'G', 'H', 'I',
|
| 41 |
+
'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V',
|
| 42 |
+
'AA', 'AR', 'AN', 'AD', 'AC', 'AE', 'AQ', 'AG', 'AH', 'AI',
|
| 43 |
+
'AL', 'AK', 'AM', 'AF', 'AP', 'AS', 'AT', 'AW', 'AY', 'AV',
|
| 44 |
+
'RA', 'RR', 'RN', 'RD', 'RC', 'RE', 'RQ', 'RG', 'RH', 'RI',
|
| 45 |
+
'RL', 'RK', 'RM', 'RF', 'RP', 'RS', 'RT', 'RW', 'RY', 'RV',
|
| 46 |
+
'NA', 'NR', 'NN', 'ND', 'NC', 'NE', 'NQ', 'NG', 'NH', 'NI',
|
| 47 |
+
'NL', 'NK', 'NM', 'NF', 'NP', 'NS', 'NT', 'NW', 'NY', 'NV',
|
| 48 |
+
'DA', 'DR', 'DN', 'DD', 'DC', 'DE', 'DQ', 'DG', 'DH', 'DI',
|
| 49 |
+
'DL', 'DK', 'DM', 'DF', 'DP', 'DS', 'DT', 'DW', 'DY', 'DV',
|
| 50 |
+
'CA', 'CR', 'CN', 'CD', 'CC', 'CE', 'CQ', 'CG', 'CH', 'CI',
|
| 51 |
+
'CL', 'CK', 'CM', 'CF', 'CP', 'CS', 'CT', 'CW', 'CY', 'CV',
|
| 52 |
+
'EA', 'ER', 'EN', 'ED', 'EC', 'EE', 'EQ', 'EG', 'EH', 'EI',
|
| 53 |
+
'EL', 'EK', 'EM', 'EF', 'EP', 'ES', 'ET', 'EW', 'EY', 'EV',
|
| 54 |
+
'QA', 'QR', 'QN', 'QD', 'QC', 'QE', 'QQ', 'QG', 'QH', 'QI',
|
| 55 |
+
'QL', 'QK', 'QM', 'QF', 'QP', 'QS', 'QT', 'QW', 'QY', 'QV',
|
| 56 |
+
'GA', 'GR', 'GN', 'GD', 'GC', 'GE', 'GQ', 'GG', 'GH', 'GI',
|
| 57 |
+
'GL', 'GK', 'GM', 'GF', 'GP', 'GS', 'GT', 'GW', 'GY', 'GV',
|
| 58 |
+
'HA', 'HR', 'HN', 'HD', 'HC', 'HE', 'HQ', 'HG', 'HH', 'HI',
|
| 59 |
+
'HL', 'HK', 'HM', 'HF', 'HP', 'HS', 'HT', 'HW', 'HY', 'HV',
|
| 60 |
+
'IA', 'IR', 'IN', 'ID', 'IC', 'IE', 'IQ', 'IG', 'IH', 'II',
|
| 61 |
+
'IL', 'IK', 'IM', 'IF', 'IP', 'IS', 'IT', 'IW', 'IY', 'IV',
|
| 62 |
+
'LA', 'LR', 'LN', 'LD', 'LC', 'LE', 'LQ', 'LG', 'LH', 'LI',
|
| 63 |
+
'LL', 'LK', 'LM', 'LF', 'LP', 'LS', 'LT', 'LW', 'LY', 'LV',
|
| 64 |
+
'KA', 'KR', 'KN', 'KD', 'KC', 'KE', 'KQ', 'KG', 'KH', 'KI',
|
| 65 |
+
'KL', 'KK', 'KM', 'KF', 'KP', 'KS', 'KT', 'KW', 'KY', 'KV',
|
| 66 |
+
'MA', 'MR', 'MN', 'MD', 'MC', 'ME', 'MQ', 'MG', 'MH', 'MI',
|
| 67 |
+
'ML', 'MK', 'MM', 'MF', 'MP', 'MS', 'MT', 'MW', 'MY', 'MV',
|
| 68 |
+
'FA', 'FR', 'FN', 'FD', 'FC', 'FE', 'FQ', 'FG', 'FH', 'FI',
|
| 69 |
+
'FL', 'FK', 'FM', 'FF', 'FP', 'FS', 'FT', 'FW', 'FY', 'FV',
|
| 70 |
+
'PA', 'PR', 'PN', 'PD', 'PC', 'PE', 'PQ', 'PG', 'PH', 'PI',
|
| 71 |
+
'PL', 'PK', 'PM', 'PF', 'PP', 'PS', 'PT', 'PW', 'PY', 'PV',
|
| 72 |
+
'SA', 'SR', 'SN', 'SD', 'SC', 'SE', 'SQ', 'SG', 'SH', 'SI',
|
| 73 |
+
'SL', 'SK', 'SM', 'SF', 'SP', 'SS', 'ST', 'SW', 'SY', 'SV',
|
| 74 |
+
'TA', 'TR', 'TN', 'TD', 'TC', 'TE', 'TQ', 'TG', 'TH', 'TI',
|
| 75 |
+
'TL', 'TK', 'TM', 'TF', 'TP', 'TS', 'TT', 'TW', 'TY', 'TV',
|
| 76 |
+
'WA', 'WR', 'WN', 'WD', 'WC', 'WE', 'WQ', 'WG', 'WH', 'WI',
|
| 77 |
+
'WL', 'WK', 'WM', 'WF', 'WP', 'WS', 'WT', 'WW', 'WY', 'WV',
|
| 78 |
+
'YA', 'YR', 'YN', 'YD', 'YC', 'YE', 'YQ', 'YG', 'YH', 'YI',
|
| 79 |
+
'YL', 'YK', 'YM', 'YF', 'YP', 'YS', 'YT', 'YW', 'YY', 'YV',
|
| 80 |
+
'VA', 'VR', 'VN', 'VD', 'VC', 'VE', 'VQ', 'VG', 'VH', 'VI',
|
| 81 |
+
'VL', 'VK', 'VM', 'VF', 'VP', 'VS', 'VT', 'VW', 'VY', 'VV'
|
| 82 |
+
]
|
| 83 |
+
|
| 84 |
+
# Wrapper to make Keras model behave like a sklearn classifier for LIME
|
| 85 |
+
def keras_predict_proba(X):
|
| 86 |
+
"""Return probabilities for both classes as [P(Non-AMP), P(AMP)]."""
|
| 87 |
+
preds = model.predict(X, verbose=0)
|
| 88 |
+
if preds.ndim == 1 or preds.shape[1] == 1:
|
| 89 |
+
preds = preds.reshape(-1, 1)
|
| 90 |
+
# Assuming sigmoid output = P(AMP); adjust if your model is reversed.
|
| 91 |
+
return np.hstack([1 - preds, preds])
|
| 92 |
+
return preds
|
| 93 |
|
| 94 |
# Dummy data for LIME
|
| 95 |
sample_data = np.random.rand(100, len(selected_features))
|
| 96 |
explainer = LimeTabularExplainer(
|
| 97 |
training_data=sample_data,
|
| 98 |
feature_names=selected_features,
|
| 99 |
+
class_names=["Non-AMP", "AMP"],
|
| 100 |
mode="classification"
|
| 101 |
)
|
| 102 |
|
| 103 |
+
# Feature extraction function (AAC + CTD only)
|
| 104 |
def extract_features(sequence):
|
| 105 |
sequence = ''.join([aa for aa in sequence.upper() if aa in "ACDEFGHIKLMNPQRSTVWY"])
|
| 106 |
if len(sequence) < 10:
|
| 107 |
return "Error: Sequence too short."
|
| 108 |
|
| 109 |
try:
|
| 110 |
+
# AAC: 20 single AAs + 400 dipeptides = 420 features
|
| 111 |
dipeptide_features = AAComposition.CalculateAADipeptideComposition(sequence)
|
| 112 |
+
filtered_aac = {k: dipeptide_features[k] for k in list(dipeptide_features.keys())[:420]}
|
| 113 |
+
|
| 114 |
+
# CTD: Composition, Transition, Distribution
|
| 115 |
ctd_features = CTD.CalculateCTD(sequence)
|
|
|
|
|
|
|
| 116 |
|
| 117 |
all_features_dict = {}
|
| 118 |
all_features_dict.update(ctd_features)
|
| 119 |
+
all_features_dict.update(filtered_aac)
|
|
|
|
|
|
|
| 120 |
|
| 121 |
feature_df_all = pd.DataFrame([all_features_dict])
|
| 122 |
normalized_array = scaler.transform(feature_df_all.values)
|
| 123 |
normalized_df = pd.DataFrame(normalized_array, columns=feature_df_all.columns)
|
| 124 |
|
| 125 |
if not set(selected_features).issubset(normalized_df.columns):
|
| 126 |
+
missing = set(selected_features) - set(normalized_df.columns)
|
| 127 |
+
return f"Error: Missing features: {list(missing)[:5]}..."
|
| 128 |
|
| 129 |
selected_df = normalized_df[selected_features].fillna(0)
|
| 130 |
+
return selected_df.values.astype(np.float32)
|
| 131 |
except Exception as e:
|
| 132 |
return f"Error in feature extraction: {str(e)}"
|
| 133 |
|
| 134 |
+
# MIC prediction function (unchanged)
|
| 135 |
def predictmic(sequence):
|
| 136 |
sequence = ''.join([aa for aa in sequence.upper() if aa in "ACDEFGHIKLMNPQRSTVWY"])
|
| 137 |
if len(sequence) < 10:
|
|
|
|
| 155 |
mic_results = {}
|
| 156 |
for bacterium, cfg in bacteria_config.items():
|
| 157 |
try:
|
| 158 |
+
mic_scaler = joblib.load(cfg["scaler"])
|
| 159 |
+
scaled = mic_scaler.transform(embedding)
|
| 160 |
transformed = joblib.load(cfg["pca"]).transform(scaled) if cfg["pca"] else scaled
|
| 161 |
+
mic_model = joblib.load(cfg["model"])
|
| 162 |
+
mic_log = mic_model.predict(transformed)[0]
|
| 163 |
mic = round(expm1(mic_log), 3)
|
| 164 |
mic_results[bacterium] = mic
|
| 165 |
except Exception as e:
|
|
|
|
| 173 |
if isinstance(features, str):
|
| 174 |
return features
|
| 175 |
|
| 176 |
+
# Keras prediction
|
| 177 |
+
raw_pred = model.predict(features, verbose=0)
|
| 178 |
+
|
| 179 |
+
# Handle sigmoid (1 output) vs softmax (>=2 outputs)
|
| 180 |
+
if raw_pred.ndim == 1 or raw_pred.shape[1] == 1:
|
| 181 |
+
prob_amp = float(raw_pred.flatten()[0]) # assume output = P(AMP)
|
| 182 |
+
if prob_amp >= 0.5:
|
| 183 |
+
prediction = 1 # AMP
|
| 184 |
+
confidence = round(prob_amp * 100, 2)
|
| 185 |
+
else:
|
| 186 |
+
prediction = 0 # Non-AMP
|
| 187 |
+
confidence = round((1 - prob_amp) * 100, 2)
|
| 188 |
+
else:
|
| 189 |
+
class_idx = int(np.argmax(raw_pred[0]))
|
| 190 |
+
prediction = class_idx
|
| 191 |
+
confidence = round(float(raw_pred[0][class_idx]) * 100, 2)
|
| 192 |
|
| 193 |
+
# Label convention: 1 = AMP, 0 = Non-AMP (swap if your model uses the opposite)
|
| 194 |
+
amp_result = "Antimicrobial Peptide (AMP)" if prediction == 1 else "Non-AMP"
|
| 195 |
result = f"Prediction: {amp_result}\nConfidence: {confidence}%\n"
|
| 196 |
|
| 197 |
+
if prediction == 1:
|
| 198 |
mic_values = predictmic(sequence)
|
| 199 |
result += "\nPredicted MIC Values (μM):\n"
|
| 200 |
for org, mic in mic_values.items():
|
|
|
|
| 202 |
else:
|
| 203 |
result += "\nMIC prediction skipped for Non-AMP sequences.\n"
|
| 204 |
|
| 205 |
+
# LIME explanation
|
| 206 |
+
try:
|
| 207 |
+
explanation = explainer.explain_instance(
|
| 208 |
+
data_row=features[0],
|
| 209 |
+
predict_fn=keras_predict_proba,
|
| 210 |
+
num_features=10
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
result += "\nTop Features Influencing Prediction:\n"
|
| 214 |
+
for feat, weight in explanation.as_list():
|
| 215 |
+
result += f"- {feat}: {round(weight, 4)}\n"
|
| 216 |
+
except Exception as e:
|
| 217 |
+
result += f"\nLIME explanation failed: {str(e)}\n"
|
| 218 |
|
| 219 |
return result
|
| 220 |
|
|
|
|
| 227 |
description="Paste an amino acid sequence (≥10 characters). Get AMP classification, MIC predictions, and LIME interpretability insights."
|
| 228 |
)
|
| 229 |
|
| 230 |
+
iface.launch(share=True)
|