File size: 4,246 Bytes
e50f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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