-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
88 lines (70 loc) · 2.62 KB
/
Copy pathtrain.py
File metadata and controls
88 lines (70 loc) · 2.62 KB
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
"""
Model Training Script — run this once before starting the server.
Pattern: Template Method (Behavioral)
Each pipeline class extends MLPipeline, implementing only build_model() and save().
The training skeleton (load → preprocess → features → train → evaluate → save)
is inherited from the base class.
Usage:
python train.py
python train.py --models rf xgb
"""
import argparse
import sys
import os
# Ensure project root is on the path
sys.path.insert(0, os.path.dirname(__file__))
from sklearn.ensemble import RandomForestClassifier
import xgboost as xgb
from backend.infrastructure.ml.ml_pipeline import MLPipeline
# =============================================================================
# Concrete Pipeline 1: Random Forest
# =============================================================================
class RandomForestPipeline(MLPipeline):
"""Template Method — ConcreteClass for Random Forest training."""
def build_model(self):
return RandomForestClassifier(
n_estimators=100,
max_depth=20,
n_jobs=-1,
random_state=42,
class_weight="balanced",
)
def save(self):
self._save_model("rf_model.pkl")
# =============================================================================
# Concrete Pipeline 2: XGBoost
# =============================================================================
class XGBoostPipeline(MLPipeline):
"""Template Method — ConcreteClass for XGBoost training."""
def build_model(self):
return xgb.XGBClassifier(
n_estimators=200,
max_depth=8,
learning_rate=0.1,
use_label_encoder=False,
eval_metric="mlogloss",
random_state=42,
n_jobs=-1,
)
def save(self):
self._save_model("xgb_model.pkl")
# =============================================================================
# Main
# =============================================================================
PIPELINE_MAP = {
"rf": RandomForestPipeline,
"xgb": XGBoostPipeline,
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Train ransomware classification models.")
parser.add_argument(
"--models", nargs="+", choices=list(PIPELINE_MAP.keys()),
default=list(PIPELINE_MAP.keys()),
help="Which models to train (default: all)",
)
args = parser.parse_args()
for key in args.models:
pipeline = PIPELINE_MAP[key]()
pipeline.run()
print("\n Training complete. Models saved to models/")
print(" Run: uvicorn backend.main:app --reload")