File size: 7,493 Bytes
f07511a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | # -*- coding: utf-8 -*-
"""Untitled17.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1GwdSjrwh3f6QCzOa8KHr_XkWy0KmZvdV
"""
import pandas as pd
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import roc_auc_score, average_precision_score, precision_recall_curve, f1_score
from sklearn.preprocessing import StandardScaler
from tqdm.auto import tqdm
import warnings
warnings.filterwarnings('ignore')
####Leave-Protein-Out Cross-Validation (LPOCV) of the mechanistic pathogenicity model.
df_features = pd.read_parquet(PATHS['data_processed'] / 'mutation_features.parquet')
df_features['disorder_x_charge'] = df_features['delta_disorder_propensity'] * df_features['delta_charge']
df_features['disorder_x_hydro'] = df_features['delta_disorder_propensity'] * df_features['delta_hydrophobicity']
df_features['ros_x_cysteine'] = df_features['ros_sensitivity'] * df_features['local_cysteine_density']
df_features['propagation_x_disorder'] = df_features['propagation_extent'] * abs(df_features['predicted_delta_disorder_mean'])
df_features['disorder_confidence_ratio'] = df_features['predicted_delta_disorder_mean'] / (df_features['predicted_delta_disorder_std'] + 0.01)
df_features['abs_delta_disorder'] = abs(df_features['delta_disorder_propensity'])
df_features['abs_delta_charge'] = abs(df_features['delta_charge'])
df_features['abs_delta_hydro'] = abs(df_features['delta_hydrophobicity'])
df_features['is_n_terminal'] = (df_features['position'] < 50).astype(int)
df_features['is_c_terminal'] = 0
df_features['is_charge_changing'] = (df_features['delta_charge'] != 0).astype(int)
df_features['is_disorder_increasing'] = (df_features['delta_disorder_propensity'] > 0).astype(int)
df_features['is_high_ros'] = (df_features['ros_sensitivity'] > 0.5).astype(int)
df_features['region_matrix'] = (df_features['region_type'] == 'matrix_idr').astype(int)
df_features['region_ims'] = (df_features['region_type'] == 'ims_idr').astype(int)
df_features['region_presequence'] = (df_features['region_type'] == 'presequence').astype(int)
df_features['region_membrane'] = (df_features['region_type'] == 'membrane_adjacent').astype(int)
df_features['has_disorder_annotation'] = df_features['in_disorder_region'].notna()
df_features['in_disorder_region'] = df_features['in_disorder_region'].fillna(False)
print(f" ✓ {len(df_features)} mutations")
print(f" ✓ {df_features['uniprot_acc'].nunique()} protéines uniques")
features_mechanistic = [
'delta_hydrophobicity', 'delta_charge', 'delta_volume',
'delta_disorder_propensity', 'delta_aromatic',
'local_charge_density', 'local_disorder_mean', 'local_disorder_variance',
'local_hydrophobicity', 'local_aromatic_density',
'local_proline_density', 'local_glycine_density', 'local_cysteine_density',
'predicted_delta_disorder_mean', 'predicted_delta_disorder_std',
'propagation_extent', 'max_effective_delta',
'delta_cpr', 'delta_ncpr', 'delta_kappa',
'ros_sensitivity', 'import_efficiency_change',
'cysteine_gained', 'cysteine_lost', 'disulfide_disruption_risk',
'oxidation_sensitivity_change',
'region_matrix', 'region_ims', 'region_presequence', 'region_membrane',
'disorder_x_charge', 'disorder_x_hydro', 'ros_x_cysteine',
'propagation_x_disorder', 'disorder_confidence_ratio',
'abs_delta_disorder', 'abs_delta_charge', 'abs_delta_hydro',
'is_n_terminal', 'is_charge_changing', 'is_disorder_increasing', 'is_high_ros'
]
def leave_protein_out_cv(df, feature_cols, model_params, threshold=None):
proteins = df['uniprot_acc'].unique()
all_y_true = []
all_y_prob = []
all_y_pred = []
protein_results = []
for protein in tqdm(proteins, desc="LPOCV"):
train_mask = df['uniprot_acc'] != protein
test_mask = df['uniprot_acc'] == protein
df_train = df[train_mask]
df_test = df[test_mask]
if len(df_test) < 2 or df_train['label'].sum() < 5:
continue
X_train = df_train[feature_cols].fillna(0).values
y_train = df_train['label'].values
X_test = df_test[feature_cols].fillna(0).values
y_test = df_test['label'].values
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
model = GradientBoostingClassifier(**model_params)
model.fit(X_train_scaled, y_train)
y_prob = model.predict_proba(X_test_scaled)[:, 1]
all_y_true.extend(y_test)
all_y_prob.extend(y_prob)
if y_test.sum() > 0:
try:
protein_auc = roc_auc_score(y_test, y_prob)
except:
protein_auc = np.nan
protein_results.append({
'protein': protein,
'n_mutations': len(y_test),
'n_pathogenic': y_test.sum(),
'auc': protein_auc
})
all_y_true = np.array(all_y_true)
all_y_prob = np.array(all_y_prob)
auc_roc = roc_auc_score(all_y_true, all_y_prob)
auc_pr = average_precision_score(all_y_true, all_y_prob)
if threshold is None:
precisions, recalls, thresholds = precision_recall_curve(all_y_true, all_y_prob)
f1_scores = 2 * (precisions * recalls) / (precisions + recalls + 1e-10)
optimal_idx = np.argmax(f1_scores)
threshold = thresholds[optimal_idx] if optimal_idx < len(thresholds) else 0.5
all_y_pred = (all_y_prob >= threshold).astype(int)
tp = ((all_y_pred == 1) & (all_y_true == 1)).sum()
fp = ((all_y_pred == 1) & (all_y_true == 0)).sum()
fn = ((all_y_pred == 0) & (all_y_true == 1)).sum()
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
return {
'auc_roc': auc_roc,
'auc_pr': auc_pr,
'threshold': threshold,
'recall': recall,
'precision': precision,
'y_true': all_y_true,
'y_prob': all_y_prob,
'protein_results': pd.DataFrame(protein_results)
}
model_params = {
'n_estimators': 200,
'max_depth': 5,
'learning_rate': 0.05,
'min_samples_split': 10,
'min_samples_leaf': 5,
'subsample': 0.8,
'random_state': 42
}
results_A = leave_protein_out_cv(df_features, features_mechanistic, model_params)
print(f" AUC-ROC: {results_A['auc_roc']:.4f}")
print(f" AUC-PR: {results_A['auc_pr']:.4f}")
print(f" Seuil: {results_A['threshold']:.3f}")
print(f" Recall: {results_A['recall']:.2%}")
print(f" Precision: {results_A['precision']:.2%}")
df_protein_results = results_A['protein_results'].dropna()
df_protein_results = df_protein_results.sort_values('n_pathogenic', ascending=False)
for _, row in df_protein_results.head(10).iterrows():
auc_str = f"{row['auc']:.2f}" if not np.isnan(row['auc']) else "N/A"
print(f" {row['protein']}: {row['n_mutations']} mut ({row['n_pathogenic']} patho) - AUC: {auc_str}")
validation_results = {
'model_A_mechanistic': {
'features': features_mechanistic,
'auc_roc': results_A['auc_roc'],
'auc_pr': results_A['auc_pr'],
'threshold': results_A['threshold'],
'recall': results_A['recall'],
'precision': results_A['precision']
},
}
import json
results_path = PATHS['evaluations'] / 'lpocv_results.json'
with open(results_path, 'w') as f:
json.dump(validation_results, f, indent=2) |