-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
48 lines (32 loc) · 1.45 KB
/
model.py
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
from typing import Union, Dict, List
import numpy as np
import yaml
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.metrics import get_scorer
from heart_disease.entities.model_config import TrainModelConfig, ModelType
from heart_disease.utils import deserialize_object, serialize_object
Classifier = Union[RandomForestClassifier, ExtraTreesClassifier]
_models = {
ModelType.random_forest: RandomForestClassifier,
ModelType.extra_trees: ExtraTreesClassifier
}
def train_model(features: np.ndarray, target: np.ndarray, config: TrainModelConfig) -> Classifier:
model = _models[config.model](random_state=config.random_state, **config.params)
model.fit(features, target)
return model
def predict_model(model: Classifier, features: np.ndarray) -> np.ndarray:
predicted = model.predict(features)
return predicted
def evaluate_model(model: Classifier, features: np.ndarray, target: np.ndarray, metrics: List[str]) -> Dict[str, float]:
metric_values = {}
for metric in metrics:
scorer = get_scorer(metric)
metric_values[metric] = scorer(model, features, target).item()
return metric_values
def save_metrics(metrics: Dict[str, float], path: str):
with open(path, "w") as f:
yaml.safe_dump(metrics, f)
def serialize_model(model: Classifier, path: str):
serialize_object(model, path)
def deserialize_model(path: str) -> Classifier:
return deserialize_object(path)