-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
70 lines (49 loc) · 2.04 KB
/
utils.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import os
import sys
import dill
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import r2_score
from src.exception import CustomException
def save_object(obj, file_path):
try:
dir_path = os.path.dirname(file_path)
os.makedirs(dir_path, exist_ok=True)
with open(file_path, 'wb') as file_obj:
dill.dump(obj, file_obj)
except Exception as e:
raise CustomException(e, sys)
def load_object(file_path:str):
try:
with open(file_path, 'rb') as file_obj:
return dill.load(file_obj)
except Exception as e:
raise CustomException(e, sys)
def evaluate_models(X_train, y_train, X_test, y_test, models:dict, hyperparams:dict):
try:
report = {}
best_model = None
best_score = float('-inf')
for model_name, model in models.items():
if model_name in hyperparams:
param_grid = hyperparams[model_name]
grid_search = GridSearchCV(model, param_grid, scoring='r2', n_jobs=3, cv = 5 , verbose=5)
grid_search.fit(X_train, y_train)
current_best_model = grid_search.best_estimator_
y_train_pred = current_best_model.predict(X_train)
y_test_pred = current_best_model.predict(X_test)
train_score = r2_score(y_train, y_train_pred)
test_score = r2_score(y_test, y_test_pred)
report[model_name] = test_score
if test_score > best_score:
best_score = test_score
best_model = current_best_model
else:
model.fit(X_train, y_train)
test_score = r2_score(y_test, model.predict(X_test))
report[model_name] = test_score
if test_score > best_score:
best_score = test_score
best_model = current_best_model
return (report, best_model)
except Exception as e:
raise CustomException(e, sys)