# webapp/services/ml_utils.py from dataclasses import dataclass from typing import List, Optional, Tuple import numpy as np import pandas as pd from sklearn.compose import ColumnTransformer from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder from sklearn.pipeline import Pipeline from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, VotingClassifier, StackingClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier try: from xgboost import XGBClassifier XGB_OK = True except Exception: XGB_OK = False # Optional balancing try: from imblearn.over_sampling import RandomOverSampler, SMOTE IMB_OK = True except Exception: IMB_OK = False NON_FEATURE_COLS = {'healthy','label','target','sample_id','id'} def get_model_from_choice(choice: str): if choice == 'rf': return RandomForestClassifier() if choice == 'svm': return SVC(probability=True) if choice == 'knn': return KNeighborsClassifier() if choice == 'lr': return LogisticRegression(max_iter=1000) if choice == 'gb': return GradientBoostingClassifier() if choice == 'xgb' and XGB_OK: return XGBClassifier(use_label_encoder=False, eval_metric='logloss') if choice == 'mlp': from sklearn.neural_network import MLPClassifier return MLPClassifier(hidden_layer_sizes=(128,64), max_iter=500) raise ValueError(f"Unsupported model choice: {choice}") def build_preprocessor(scaler_key: str, X: pd.DataFrame) -> ColumnTransformer: num_cols = X.select_dtypes(include='number').columns.tolist() cat_cols = X.select_dtypes(exclude='number').columns.tolist() scaler = StandardScaler() if scaler_key == 'standard' else MinMaxScaler() return ColumnTransformer( transformers=[ ('num', scaler, num_cols), ('cat', OneHotEncoder(handle_unknown='ignore', sparse_output=False), cat_cols), ], remainder='drop', verbose_feature_names_out=False, ) def build_estimator(base_models: List[str], meta_learner: str, ensemble_type: str, voting_type: str): estimators = [(k, get_model_from_choice(k)) for k in base_models] if len(estimators) == 0: raise ValueError("Select at least one base model.") if len(estimators) >= 2 and ensemble_type == 'none': ensemble_type = 'stacking' # server-side guard if ensemble_type == 'voting': return VotingClassifier(estimators=estimators, voting=voting_type) if ensemble_type == 'stacking': meta = get_model_from_choice(meta_learner) return StackingClassifier(estimators=estimators, final_estimator=meta) return estimators[0][1] def apply_balancing(X: pd.DataFrame, y: pd.Series, strategy: str, target_samples: Optional[int]) -> Tuple[pd.DataFrame, pd.Series]: """Applies optional balancing. SMOTE/oversampling via imblearn; GAN hooks left for you to plug in.""" if strategy == 'none': return X, y if strategy == 'over': if not IMB_OK: raise RuntimeError("imblearn not installed for RandomOverSampler.") ros = RandomOverSampler() Xr, yr = ros.fit_resample(X, y) return Xr, yr if strategy == 'smote': if not IMB_OK: raise RuntimeError("imblearn not installed for SMOTE.") sm = SMOTE() Xr, yr = sm.fit_resample(X, y) return Xr, yr if strategy == 'gans': # 🔌 hook your GAN generator here; placeholder pass-through: # from your_module import synthesize_with_gan # Xr, yr = synthesize_with_gan(X, y, target_samples=target_samples) return X, y # no-op by default return X, y def apply_augmentation(X_train: pd.DataFrame, y_train: pd.Series, augmentation: str, target_samples: Optional[int]) -> Tuple[pd.DataFrame, pd.Series]: if augmentation == 'none': return X_train, y_train if augmentation == 'gans': # 🔌 hook GAN augmentation for the training fold only return X_train, y_train # no-op by default return X_train, y_train