Update model/train_and_save.py
Browse files- model/train_and_save.py +142 -119
model/train_and_save.py
CHANGED
|
@@ -1,119 +1,142 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
import
|
| 10 |
-
|
| 11 |
-
import
|
| 12 |
-
|
| 13 |
-
from sklearn.
|
| 14 |
-
from sklearn.
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Import required libraries
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
import joblib
|
| 6 |
+
|
| 7 |
+
# Scikit-learn imports for building ML pipeline
|
| 8 |
+
from sklearn.compose import ColumnTransformer
|
| 9 |
+
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
| 10 |
+
from sklearn.impute import SimpleImputer
|
| 11 |
+
from sklearn.linear_model import LogisticRegression
|
| 12 |
+
from sklearn.pipeline import Pipeline
|
| 13 |
+
from sklearn.model_selection import train_test_split
|
| 14 |
+
from sklearn.metrics import classification_report, roc_auc_score
|
| 15 |
+
|
| 16 |
+
DATA_PATH = Path("C:\Users\wissa\Downloads\data\stroke-flask-docker\data\healthcare-dataset-stroke-data.csv")
|
| 17 |
+
OUT_PATH = Path("C:\Users\wissa\Downloads\data\stroke-flask-docker\model\stroke_pipeline.joblib")
|
| 18 |
+
OUT_PATH.parent.mkdir(parents=True, exist_ok=True) # Make sure output folder exists
|
| 19 |
+
|
| 20 |
+
# Define feature groups
|
| 21 |
+
CATEGORICAL = ["gender","ever_married","work_type","Residence_type","smoking_status"]
|
| 22 |
+
NUMERIC = ["age","avg_glucose_level","bmi"]
|
| 23 |
+
BINARY_INT = ["hypertension","heart_disease"] # Already numeric (0/1), but treated separately
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load_real_or_synthetic():
|
| 27 |
+
if DATA_PATH.exists():
|
| 28 |
+
# Load dataset from CSV
|
| 29 |
+
df = pd.read_csv(DATA_PATH)
|
| 30 |
+
|
| 31 |
+
# Define which columns we MUST have
|
| 32 |
+
must_have = ["gender","age","hypertension","heart_disease","ever_married",
|
| 33 |
+
"work_type","Residence_type","avg_glucose_level","bmi",
|
| 34 |
+
"smoking_status","stroke"]
|
| 35 |
+
|
| 36 |
+
# Check if any required columns are missing
|
| 37 |
+
missing = set(must_have) - set(df.columns)
|
| 38 |
+
if missing:
|
| 39 |
+
raise ValueError(f"Dataset is missing columns: {missing}")
|
| 40 |
+
|
| 41 |
+
# Drop extra columns like "id" if present, keep only required ones
|
| 42 |
+
df = df[[c for c in df.columns if c in must_have]]
|
| 43 |
+
return df
|
| 44 |
+
else:
|
| 45 |
+
# If dataset file is not found, generate synthetic (random but realistic) data
|
| 46 |
+
rng = np.random.RandomState(42) # Random seed for reproducibility
|
| 47 |
+
N = 2000 # number of synthetic rows
|
| 48 |
+
|
| 49 |
+
# Generate random values for each feature
|
| 50 |
+
df = pd.DataFrame({
|
| 51 |
+
"gender": rng.choice(["Male","Female","Other"], size=N, p=[0.49,0.50,0.01]),
|
| 52 |
+
"age": rng.randint(1, 90, size=N),
|
| 53 |
+
"hypertension": rng.binomial(1, 0.15, size=N), # 15% chance of hypertension
|
| 54 |
+
"heart_disease": rng.binomial(1, 0.08, size=N), # 8% chance of heart disease
|
| 55 |
+
"ever_married": rng.choice(["Yes","No"], size=N, p=[0.7,0.3]),
|
| 56 |
+
"work_type": rng.choice(["Private","Self-employed","Govt_job","children","Never_worked"],
|
| 57 |
+
size=N, p=[0.6,0.2,0.18,0.01,0.01]),
|
| 58 |
+
"Residence_type": rng.choice(["Urban","Rural"], size=N, p=[0.55,0.45]),
|
| 59 |
+
"avg_glucose_level": rng.normal(100, 30, size=N).clip(50, 300), # realistic range
|
| 60 |
+
"bmi": rng.normal(28, 6, size=N).clip(10, 60),
|
| 61 |
+
"smoking_status": rng.choice(["formerly smoked","never smoked","smokes","Unknown"],
|
| 62 |
+
size=N, p=[0.2,0.6,0.15,0.05]),
|
| 63 |
+
})
|
| 64 |
+
|
| 65 |
+
# Define a "logit" (linear combination of features) that influences stroke probability
|
| 66 |
+
logit = (
|
| 67 |
+
0.03*df["age"] +
|
| 68 |
+
0.02*(df["avg_glucose_level"]-100) +
|
| 69 |
+
0.05*(df["bmi"]-28) +
|
| 70 |
+
0.8*df["hypertension"] +
|
| 71 |
+
0.9*df["heart_disease"] +
|
| 72 |
+
0.3*(df["ever_married"]=="Yes").astype(int)
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Convert logit to probability using sigmoid function
|
| 76 |
+
prob = 1/(1+np.exp(- (logit-4.0))) # shift so stroke is rare (imbalanced dataset)
|
| 77 |
+
|
| 78 |
+
# Assign stroke label (1 = stroke, 0 = no stroke) based on probability
|
| 79 |
+
df["stroke"] = (rng.rand(len(df)) < prob).astype(int)
|
| 80 |
+
return df
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def build_pipeline():
|
| 84 |
+
# For categorical features: fill missing with most frequent, then one-hot encode
|
| 85 |
+
cat_proc = Pipeline(steps=[
|
| 86 |
+
("impute", SimpleImputer(strategy="most_frequent")),
|
| 87 |
+
("ohe", OneHotEncoder(handle_unknown="ignore"))
|
| 88 |
+
])
|
| 89 |
+
|
| 90 |
+
# For numeric features: fill missing with median, then scale to mean=0, std=1
|
| 91 |
+
num_proc = Pipeline(steps=[
|
| 92 |
+
("impute", SimpleImputer(strategy="median")),
|
| 93 |
+
("scale", StandardScaler())
|
| 94 |
+
])
|
| 95 |
+
|
| 96 |
+
# For binary integer features: impute, then scale (optional but safe for pipeline)
|
| 97 |
+
bin_proc = Pipeline(steps=[
|
| 98 |
+
("impute", SimpleImputer(strategy="most_frequent")),
|
| 99 |
+
("scale", StandardScaler(with_mean=False)) # keep sparse-friendly format
|
| 100 |
+
])
|
| 101 |
+
|
| 102 |
+
# Combine all processors into one column transformer
|
| 103 |
+
pre = ColumnTransformer(transformers=[
|
| 104 |
+
("cat", cat_proc, CATEGORICAL),
|
| 105 |
+
("num", num_proc, NUMERIC),
|
| 106 |
+
("bin", bin_proc, BINARY_INT),
|
| 107 |
+
])
|
| 108 |
+
|
| 109 |
+
# Define classifier (logistic regression for binary classification)
|
| 110 |
+
clf = LogisticRegression(max_iter=1000, n_jobs=None)
|
| 111 |
+
|
| 112 |
+
# Final pipeline: preprocessing → model
|
| 113 |
+
pipeline = Pipeline([("pre", pre), ("clf", clf)])
|
| 114 |
+
return pipeline
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def main():
|
| 118 |
+
df = load_real_or_synthetic()
|
| 119 |
+
|
| 120 |
+
# Split into features (X) and target (y = stroke)
|
| 121 |
+
X = df.drop(columns=["stroke"])
|
| 122 |
+
y = df["stroke"].astype(int)
|
| 123 |
+
|
| 124 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 125 |
+
X, y, test_size=0.2, random_state=42, stratify=y
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
pipeline = build_pipeline()
|
| 129 |
+
pipeline.fit(X_train, y_train)
|
| 130 |
+
|
| 131 |
+
y_prob = pipeline.predict_proba(X_test)[:,1] # probability of stroke
|
| 132 |
+
y_pred = (y_prob >= 0.3).astype(int) # classify as 1 if prob ≥ 0.3
|
| 133 |
+
|
| 134 |
+
print("AUC:", roc_auc_score(y_test, y_prob)) # area under ROC curve
|
| 135 |
+
print("Report:\n", classification_report(y_test, y_pred)) # precision/recall/F1
|
| 136 |
+
|
| 137 |
+
joblib.dump(pipeline, OUT_PATH)
|
| 138 |
+
print(f"Saved pipeline to {OUT_PATH.resolve()}")
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
main()
|