File size: 5,936 Bytes
b00da5f | 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 |
import argparse, os, joblib, numpy as np, pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import roc_auc_score, average_precision_score, f1_score, r2_score, mean_absolute_error
DEFAULT_FEATURES = [
"ecm_total_protein_mgml","pre_pH","pre_conductivity_mS","temp_incubation_C",
"uv_ratio_A220_A280","sds_smear_index","sds_alpha_ratio",
"DMEM_percent","PBS_10x_uL_per_mL","NaCl_mM_added","CaCl2_mM_added",
"target_pH",
# Advanced biochemical assays (optional)
"hydroxyproline_mgml","dmmB_GAG_ugml","viscosity_proxy_sec",
# Pre-gel viscosity (Scientific Reports 2019) (optional)
"pre_gel_viscosity_mPas","pre_gel_viscosity_temp_C","shear_rate_s_minus1",
# Turbidity/gelation kinetics (Scientific Reports 2019, MDPI 2021) (optional)
"turbidity_lag_time_min","turbidity_t_half_min","turbidity_slope_per_min",
# Viscoelastic/rheological properties (Saldin et al. 2016, Brazdaru et al. 2015) (optional)
"storage_modulus_G_prime_Pa","loss_modulus_G_double_prime_Pa","tan_delta",
# Residual contaminants (cornea ECM study 2019) (optional)
"sds_residual_ppm","detergent_residual_binary","cytotoxicity_score_0to3",
# Micro-DSC parameters (optional)
"dsc_onset_T_C","dsc_peak_T_C","dsc_delta_H_J_g",
# Circular Dichroism parameters (optional)
"cd_molar_ellipticity_222nm_mdeg","cd_helix_percent",
# FTIR parameters (optional)
"ftir_amide3_1450_ratio",
# Additional residual contaminants (optional)
"dna_residual_ng_mg","endotoxin_residual_EU_mg","protease_residual_U_mg",
# Swelling ratio parameters (optional)
"swelling_ratio_Q","gel_fresh_weight_mg","gel_swollen_weight_mg","gel_dry_weight_mg",
# Enzymatic degradation parameters (optional)
"enzymatic_degradation_t_half_min","collagenase_concentration_U_mL",
# Diffusion/FRAP parameters (optional)
"diffusion_coefficient_um2_s","frap_t_half_s","probe_radius_um",
# Quality control metrics (optional)
"gel_strength_score_0to3","syneresis_binary"
]
TARGET_CLS = "gel_binary"
TARGET_REG = "time_to_halfmax_min"
def load_dataset(path):
df = pd.read_csv(path)
df_cls = df.dropna(subset=[TARGET_CLS]) if TARGET_CLS in df.columns else pd.DataFrame()
df_reg = df.dropna(subset=[TARGET_REG, TARGET_CLS]) if (TARGET_REG in df.columns and TARGET_CLS in df.columns) else pd.DataFrame()
return df, df_cls, df_reg
def build_classifier(numeric_features):
pre = ColumnTransformer([("num", Pipeline([("imp", SimpleImputer(strategy="median")),
("sc", StandardScaler())]), numeric_features)])
base = LogisticRegression(max_iter=2000, class_weight="balanced", solver="lbfgs")
pipe = Pipeline([("pre", pre), ("clf", base)])
clf = CalibratedClassifierCV(pipe, method="isotonic", cv=3)
return clf
def build_regressor(numeric_features):
pre = ColumnTransformer([("num", Pipeline([("imp", SimpleImputer(strategy="median")),
("sc", StandardScaler())]), numeric_features)])
reg = RandomForestRegressor(n_estimators=300, random_state=42, n_jobs=-1)
pipe = Pipeline([("pre", pre), ("reg", reg)])
return pipe
def main(args):
os.makedirs("models", exist_ok=True)
df, df_cls, df_reg = load_dataset(args.csv)
features = [c for c in DEFAULT_FEATURES if c in df.columns]
if not features:
raise SystemExit("No expected feature columns found. Please include DEFAULT_FEATURES in your CSV.")
# Classification
if len(df_cls) >= 4:
Xc, yc = df_cls[features], df_cls[TARGET_CLS].astype(int)
try:
Xc_tr, Xc_te, yc_tr, yc_te = train_test_split(Xc, yc, test_size=0.25, stratify=yc, random_state=42)
except ValueError:
Xc_tr, Xc_te, yc_tr, yc_te = train_test_split(Xc, yc, test_size=0.25, random_state=42)
clf = build_classifier(features)
clf.fit(Xc_tr, yc_tr)
proba = clf.predict_proba(Xc_te)[:,1]
auc = roc_auc_score(yc_te, proba) if len(np.unique(yc_te))>1 else np.nan
ap = average_precision_score(yc_te, proba) if len(np.unique(yc_te))>1 else np.nan
f1 = f1_score(yc_te, (proba>=0.5).astype(int)) if len(np.unique(yc_te))>1 else np.nan
print(f"[Classifier] ROC-AUC={auc:.3f} AP={ap:.3f} F1@0.5={f1:.3f}")
joblib.dump({"model": clf, "features": features}, "models/gel_classifier.joblib")
else:
print("Not enough rows to train classifier (need >=4). Skipping.")
# Regression on positive gels
if len(df_reg) >= 6:
df_reg_ok = df_reg[df_reg[TARGET_CLS]==1].copy()
if len(df_reg_ok) >= 5:
Xr, yr = df_reg_ok[features], df_reg_ok[TARGET_REG].astype(float)
Xr_tr, Xr_te, yr_tr, yr_te = train_test_split(Xr, yr, test_size=0.25, random_state=42)
reg = build_regressor(features)
reg.fit(Xr_tr, yr_tr)
pred = reg.predict(Xr_te)
r2 = r2_score(yr_te, pred)
mae = mean_absolute_error(yr_te, pred)
print(f"[Regressor] R2={r2:.3f} MAE={mae:.2f} min")
joblib.dump({"model": reg, "features": features}, "models/thalf_regressor.joblib")
else:
print("Not enough positive gels to train regressor (need >=5). Skipping.")
else:
print("Not enough rows to consider regression (need >=6). Skipping.")
print("Done.")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--csv", type=str, default="data/ecm_gelation_dataset_template.csv")
main(ap.parse_args())
|