Download utils/tabular_predictor.py from DheivaCodes/PCOS_Detection_Integrated_System: direct link, hf CLI and curl.
- Browser
- Download file 8.57 kB
-
https://huggingface.co/spaces/DheivaCodes/PCOS_Detection_Integrated_System/resolve/main/utils/tabular_predictor.py
- Command line
-
hf download hf://spaces/DheivaCodes/PCOS_Detection_Integrated_System/utils/tabular_predictor.py
-
curl -L -o tabular_predictor.py https://huggingface.co/spaces/DheivaCodes/PCOS_Detection_Integrated_System/resolve/main/utils/tabular_predictor.py
8.57 kB
| """ | |
| Tabular predictor — loads saved artifacts from B13 of the PCOS pipeline | |
| and runs the full inference chain: | |
| clean → impute → scale → domain severity → base models → ensemble meta | |
| """ | |
| import os | |
| import re | |
| import copy | |
| import numpy as np | |
| import pandas as pd | |
| import joblib | |
| DEPLOY_DIR = os.path.join(os.path.dirname(__file__), "..", "models") | |
| DOMAIN_WEIGHTS = { | |
| "METABOLIC" : 0.35, | |
| "REPRODUCTIVE" : 0.40, | |
| "HYPERANDROGENIC": 0.20, | |
| "GENERAL" : 0.05, | |
| } | |
| BIOMARKER_DIRECTIONS = { | |
| "FSH(mIU/mL)" : 1, | |
| "LH(mIU/mL)" : -1, | |
| "FSH/LH" : 1, | |
| "AMH(ng/mL)" : -1, | |
| "Follicle No. (L)" : -1, | |
| "Follicle No. (R)" : -1, | |
| "Endometrium (mm)" : -1, | |
| "PRG(ng/mL)" : -1, | |
| "Cycle(R/I)" : 1, | |
| } | |
| BIOMARKER_WEIGHTS = { | |
| "FSH(mIU/mL)" : 0.18, | |
| "LH(mIU/mL)" : 0.08, | |
| "FSH/LH" : 0.15, | |
| "AMH(ng/mL)" : 0.22, | |
| "Follicle No. (L)" : 0.10, | |
| "Follicle No. (R)" : 0.10, | |
| "Endometrium (mm)" : 0.08, | |
| "PRG(ng/mL)" : 0.05, | |
| "Cycle(R/I)" : 0.04, | |
| } | |
| PCOS_RISK_LABELS = { | |
| "Low" : "Low PCOS Risk", | |
| "Moderate" : "Moderate PCOS Risk", | |
| "High" : "High PCOS Risk", | |
| } | |
| INFERTILITY_RISK_LABELS = { | |
| "Low" : "Low Infertility Risk", | |
| "Moderate" : "Moderate Infertility Risk", | |
| "High" : "High Infertility Risk", | |
| } | |
| def clean_name(name: str) -> str: | |
| return re.sub(r"[^0-9a-zA-Z_]", "_", name.strip()) | |
| def load_tabular_artifacts(): | |
| """Load all pkl artifacts saved by the pipeline's B13.""" | |
| arts = {} | |
| files = { | |
| "meta" : "ensemble_meta.pkl", | |
| "base_models" : "base_models.pkl", | |
| "domain_models" : "domain_models.pkl", | |
| "mice" : "mice_imputer.pkl", | |
| "scaler" : "scaler.pkl", | |
| "stats" : "train_stats.pkl", | |
| "feat_cols" : "feature_columns.pkl", | |
| "threshold" : "best_threshold.pkl", | |
| } | |
| for key, fname in files.items(): | |
| path = os.path.join(DEPLOY_DIR, fname) | |
| if os.path.exists(path): | |
| arts[key] = joblib.load(path) | |
| else: | |
| arts[key] = None | |
| return arts | |
| def _apply_severity(domain_models, stats, X_raw_df, X_sc_df): | |
| """Mirror of apply_severity() from the main pipeline.""" | |
| result = pd.DataFrame(index=X_raw_df.index) | |
| for d, (model, fc) in domain_models.items(): | |
| available_fc = [c for c in fc if c in X_sc_df.columns] | |
| if not available_fc: | |
| result[f"{d}_SEV"] = 0.0 | |
| continue | |
| p = model.predict_proba(X_sc_df[available_fc])[:, 1] | |
| mn, mx = stats[d]["min"], stats[d]["max"] | |
| result[f"{d}_SEV"] = np.clip((p - mn) / (mx - mn + 1e-6), 0, 1) | |
| result = result.fillna(0) | |
| result["OVERALL_SEV"] = sum( | |
| result[f"{d}_SEV"] * DOMAIN_WEIGHTS[d] | |
| for d in DOMAIN_WEIGHTS if f"{d}_SEV" in result | |
| ) | |
| return result | |
| def predict_tabular(arts: dict, patient_dict: dict) -> dict: | |
| """ | |
| Run full tabular inference on a single patient. | |
| patient_dict: {feature_name: value} using original column names | |
| Returns: pcos_prob, pcos_prediction, severity scores, infertility risk score | |
| """ | |
| feat_cols = arts["feat_cols"] # list of cleaned column names | |
| # Build raw input DataFrame with original names | |
| raw = pd.DataFrame([patient_dict]) | |
| # Compute FSH/LH ratio if both present | |
| if "FSH(mIU/mL)" in raw.columns and "LH(mIU/mL)" in raw.columns: | |
| raw["FSH_LH_Ratio"] = raw["FSH(mIU/mL)"] / (raw["LH(mIU/mL)"] + 1e-6) | |
| if "Follicle No. (L)" in raw.columns and "Follicle No. (R)" in raw.columns: | |
| raw["Total_Follicles"] = (raw["Follicle No. (L)"].fillna(0) + | |
| raw["Follicle No. (R)"].fillna(0)) | |
| if "AMH(ng/mL)" in raw.columns and "FSH(mIU/mL)" in raw.columns: | |
| raw["AMH_FSH_Ratio"] = raw["AMH(ng/mL)"] / (raw["FSH(mIU/mL)"] + 1e-6) | |
| if "BMI" in raw.columns and "Waist(inch)" in raw.columns: | |
| raw["BMI_Waist_Ratio"] = raw["BMI"] / (raw["Waist(inch)"] + 1e-6) | |
| andro_feats = ["hair growth(Y/N)", "Skin darkening (Y/N)", | |
| "Hair loss(Y/N)", "Pimples(Y/N)", "PRL(ng/mL)"] | |
| present_andro = [f for f in andro_feats if f in raw.columns] | |
| if present_andro: | |
| raw["Androgenic_Score"] = raw[present_andro].sum(axis=1) | |
| # Clean column names | |
| raw_clean = raw.copy() | |
| raw_clean.columns = [clean_name(c) for c in raw_clean.columns] | |
| # Align to training columns — fill missing with NaN | |
| X = pd.DataFrame(columns=feat_cols) | |
| X = pd.concat([X, raw_clean.reindex(columns=feat_cols)], ignore_index=True) | |
| X = X.astype(float) | |
| X_raw_for_severity = X.copy() | |
| # Impute | |
| mice = arts["mice"] | |
| num_c = X.select_dtypes(include=np.number).columns | |
| X_imp = pd.DataFrame(mice.transform(X), columns=X.columns, index=X.index) | |
| # Scale | |
| scaler = arts["scaler"] | |
| X_sc = X_imp.copy() | |
| X_sc[num_c] = scaler.transform(X_imp[num_c]) | |
| # Domain severity | |
| sev = _apply_severity(arts["domain_models"], arts["stats"], | |
| X_raw_for_severity, X_sc) | |
| # Final feature matrix | |
| X_final = pd.concat([X_sc, sev], axis=1) | |
| # Ensure columns match training | |
| for c in arts["feat_cols"] + list(sev.columns): | |
| if c not in X_final.columns: | |
| X_final[c] = 0.0 | |
| # Base model probabilities | |
| base_probs = {} | |
| for name, model in arts["base_models"].items(): | |
| try: | |
| cols_needed = [c for c in X_final.columns if c in | |
| (arts["feat_cols"] + list(sev.columns))] | |
| base_probs[name] = model.predict_proba(X_final)[:, 1][0] | |
| except Exception: | |
| base_probs[name] = 0.5 | |
| # Meta-learner | |
| meta_input = pd.DataFrame([base_probs]) | |
| pcos_prob = arts["meta"].predict_proba(meta_input)[:, 1][0] | |
| threshold = arts["threshold"] | |
| prediction = "PCOS" if pcos_prob >= threshold else "Not PCOS" | |
| # PCOS risk tier | |
| if pcos_prob < 0.33: | |
| pcos_tier = "Low" | |
| elif pcos_prob < 0.66: | |
| pcos_tier = "Moderate" | |
| else: | |
| pcos_tier = "High" | |
| # Severity domain scores | |
| domain_scores = { | |
| d: round(float(sev[f"{d}_SEV"].iloc[0]), 4) | |
| for d in DOMAIN_WEIGHTS if f"{d}_SEV" in sev.columns | |
| } | |
| overall_sev = round(float(sev["OVERALL_SEV"].iloc[0]), 4) | |
| # Infertility risk score from biomarkers | |
| infertility_score, infertility_tier = _compute_infertility_risk(patient_dict) | |
| return { | |
| "pcos_prob" : round(float(pcos_prob), 4), | |
| "pcos_prediction" : prediction, | |
| "pcos_tier" : pcos_tier, | |
| "threshold" : round(float(threshold), 4), | |
| "base_probs" : {k: round(v, 4) for k, v in base_probs.items()}, | |
| "domain_scores" : domain_scores, | |
| "overall_severity" : overall_sev, | |
| "infertility_score": round(infertility_score, 4), | |
| "infertility_tier" : infertility_tier, | |
| } | |
| def _compute_infertility_risk(patient_dict: dict) -> tuple: | |
| """ | |
| Compute infertility risk score from raw biomarkers. | |
| Returns (score 0–1, tier string). | |
| """ | |
| from sklearn.preprocessing import MinMaxScaler | |
| # Map patient_dict keys to biomarker keys | |
| key_map = { | |
| "AMH(ng/mL)" : "AMH(ng/mL)", | |
| } | |
| avail = {f: patient_dict.get(f) for f in BIOMARKER_WEIGHTS | |
| if patient_dict.get(f) is not None} | |
| if not avail: | |
| return 0.5, "Moderate" | |
| # Simple weighted score — normalise each feature relative to known ranges | |
| CLINICAL_RANGES = { | |
| "FSH(mIU/mL)" : (1.0, 30.0), | |
| "LH(mIU/mL)" : (0.5, 40.0), | |
| "FSH/LH" : (0.1, 5.0), | |
| "AMH(ng/mL)" : (0.1, 15.0), | |
| "Follicle No. (L)" : (0.0, 25.0), | |
| "Follicle No. (R)" : (0.0, 25.0), | |
| "Endometrium (mm)" : (2.0, 16.0), | |
| "PRG(ng/mL)" : (0.1, 25.0), | |
| "Cycle(R/I)" : (0.0, 1.0), | |
| } | |
| score = 0.0 | |
| total_w = 0.0 | |
| for feat, val in avail.items(): | |
| lo, hi = CLINICAL_RANGES.get(feat, (0, 1)) | |
| norm = np.clip((float(val) - lo) / (hi - lo + 1e-6), 0, 1) | |
| # Orient | |
| if BIOMARKER_DIRECTIONS.get(feat, 1) == -1: | |
| norm = 1 - norm | |
| w = BIOMARKER_WEIGHTS.get(feat, 0.1) | |
| score += w * norm | |
| total_w += w | |
| if total_w > 0: | |
| score /= total_w | |
| if score < 0.33: | |
| tier = "Low" | |
| elif score < 0.66: | |
| tier = "Moderate" | |
| else: | |
| tier = "High" | |
| return score, tier | |