| |
| """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') |
|
|
| |
|
|
|
|
| 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) |