-
Notifications
You must be signed in to change notification settings - Fork 3
/
__init__.py
253 lines (221 loc) · 11.7 KB
/
__init__.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import sys
import logging
import importlib
import numpy as np
import yaml
import os
import sys
from collections import namedtuple
from typing import List
from neuro_mf.constant import *
logger = logging.getLogger(__name__)
__version__ = "0.0.5"
InitializedModelDetail = namedtuple("InitializedModelDetail",
["model_serial_number", "model", "param_grid_search", "model_name"])
GridSearchedBestModel = namedtuple("GridSearchedBestModel", ["model_serial_number",
"model",
"best_model",
"best_parameters",
"best_score",
])
BestModel = namedtuple("BestModel", ["model_serial_number",
"model",
"best_model",
"best_parameters",
"best_score", ])
class ModelFactory:
def __init__(self, model_config_path: str = None,
):
"""
model_config_path
"""
try:
self.config: dict = ModelFactory.read_params(model_config_path)
self.grid_search_cv_module: str = self.config[GRID_SEARCH_KEY][MODULE_KEY]
self.grid_search_class_name: str = self.config[GRID_SEARCH_KEY][CLASS_KEY]
self.grid_search_property_data: dict = dict(self.config[GRID_SEARCH_KEY][PARAM_KEY])
self.models_initialization_config: dict = dict(self.config[MODEL_SELECTION_KEY])
self.initialized_model_list = None
self.grid_searched_best_model_list = None
except Exception as e:
raise e
@staticmethod
def update_property_of_class(instance_ref, property_data: dict):
try:
if not isinstance(property_data, dict):
raise Exception("property_data parameter required to dictionary")
logger.info(property_data)
for key, value in property_data.items():
setattr(instance_ref, key, value)
return instance_ref
except Exception as e:
raise e
@staticmethod
def read_params(config_path: str) -> dict:
try:
with open(config_path) as yaml_file:
config = yaml.safe_load(yaml_file)
return config
except Exception as e:
raise e
@staticmethod
def class_for_name(module_name, class_name):
"""
This function is equivalent to
from module_name import class_name
return: class_name
"""
try:
# load the module, will raise ImportError if module cannot be loaded
module = importlib.import_module(module_name)
# get the class, will raise AttributeError if class cannot be found
class_ref = getattr(module, class_name)
return class_ref
except Exception as e:
raise e
def execute_grid_search_operation(self, initialized_model: InitializedModelDetail, input_feature,
output_feature) -> GridSearchedBestModel:
"""
excute_grid_search_operation(): function will perform paramter search operation and
it will return you the best optimistic model with best paramter:
estimator: Model object
param_grid: dictionary of paramter to perform search operation
input_feature: your all input features
output_feature: Target/Dependent features
================================================================================
return: Function will return GridSearchOperation object
"""
try:
# instantiating GridSearchCV class
message = "*" * 50, f"training {type(initialized_model.model).__name__}", "*" * 50
logger.info(message)
grid_search_cv_ref = ModelFactory.class_for_name(module_name=self.grid_search_cv_module,
class_name=self.grid_search_class_name
)
grid_search_cv = grid_search_cv_ref(estimator=initialized_model.model,
param_grid=initialized_model.param_grid_search)
grid_search_cv = ModelFactory.update_property_of_class(grid_search_cv,
self.grid_search_property_data)
grid_search_cv.fit(input_feature, output_feature)
grid_searched_best_model = GridSearchedBestModel(model_serial_number=initialized_model.model_serial_number,
model=initialized_model.model,
best_model=grid_search_cv.best_estimator_,
best_parameters=grid_search_cv.best_params_,
best_score=grid_search_cv.best_score_
)
return grid_searched_best_model
except Exception as e:
raise e
def get_initialized_model_list(self) -> List[InitializedModelDetail]:
"""
This function will return a list of model details.
return List[ModelDetail]
"""
try:
initialized_model_list = []
for model_serial_number in self.models_initialization_config.keys():
model_initialization_config = self.models_initialization_config[model_serial_number]
model_obj_ref = ModelFactory.class_for_name(module_name=model_initialization_config[MODULE_KEY],
class_name=model_initialization_config[CLASS_KEY]
)
model = model_obj_ref()
if PARAM_KEY in model_initialization_config:
model_obj_property_data = dict(model_initialization_config[PARAM_KEY])
model = ModelFactory.update_property_of_class(instance_ref=model,
property_data=model_obj_property_data)
param_grid_search = model_initialization_config[SEARCH_PARAM_GRID_KEY]
model_name = f"{model_initialization_config[MODULE_KEY]}.{model_initialization_config[CLASS_KEY]}"
model_initialization_config = InitializedModelDetail(model_serial_number=model_serial_number,
model=model,
param_grid_search=param_grid_search,
model_name=model_name
)
initialized_model_list.append(model_initialization_config)
self.initialized_model_list = initialized_model_list
return self.initialized_model_list
except Exception as e:
raise e
def initiate_best_parameter_search_for_initialized_model(self, initialized_model: InitializedModelDetail,
input_feature,
output_feature) -> GridSearchedBestModel:
"""
initiate_best_model_parameter_search(): function will perform paramter search operation and
it will return you the best optimistic model with best paramter:
estimator: Model object
param_grid: dictionary of paramter to perform search operation
input_feature: your all input features
output_feature: Target/Dependent features
================================================================================
return: Function will return a GridSearchOperation
"""
try:
return self.execute_grid_search_operation(initialized_model=initialized_model,
input_feature=input_feature,
output_feature=output_feature)
except Exception as e:
raise e
def initiate_best_parameter_search_for_initialized_models(self,
initialized_model_list: List[InitializedModelDetail],
input_feature,
output_feature) -> List[GridSearchedBestModel]:
try:
self.grid_searched_best_model_list = []
for initialized_model_list in initialized_model_list:
grid_searched_best_model = self.initiate_best_parameter_search_for_initialized_model(
initialized_model=initialized_model_list,
input_feature=input_feature,
output_feature=output_feature
)
self.grid_searched_best_model_list.append(grid_searched_best_model)
return self.grid_searched_best_model_list
except Exception as e:
raise e
@staticmethod
def get_model_detail(model_details: List[InitializedModelDetail],
model_serial_number: str) -> InitializedModelDetail:
"""
This function return ModelDetail
"""
try:
for model_data in model_details:
if model_data.model_serial_number == model_serial_number:
return model_data
except Exception as e:
raise e
@staticmethod
def get_best_model_from_grid_searched_best_model_list(grid_searched_best_model_list: List[GridSearchedBestModel],
base_accuracy=0.6
) -> BestModel:
try:
best_model = None
for grid_searched_best_model in grid_searched_best_model_list:
if base_accuracy < grid_searched_best_model.best_score:
logger.info(f"Acceptable model found:{grid_searched_best_model}")
base_accuracy = grid_searched_best_model.best_score
best_model = grid_searched_best_model
if not best_model:
raise Exception(f"None of Model has base accuracy: {base_accuracy}")
logger.info(f"Best model: {best_model}")
return best_model
except Exception as e:
raise e
def get_best_model(self, X, y, base_accuracy=0.6) -> BestModel:
"""
X: input feature
y: Target feature
base_accuracy: set expected accuracy if model is not able to provide required accuracy
exception will be raised.
"""
try:
logger.info("Started Initializing model from config file")
initialized_model_list = self.get_initialized_model_list()
logger.info(f"Initialized model: {initialized_model_list}")
grid_searched_best_model_list = self.initiate_best_parameter_search_for_initialized_models(
initialized_model_list=initialized_model_list,
input_feature=X,
output_feature=y
)
return ModelFactory.get_best_model_from_grid_searched_best_model_list(grid_searched_best_model_list,
base_accuracy=base_accuracy)
except Exception as e:
raise e