1
|
|
|
""" |
2
|
|
|
Abstract class for SKLearn Classifiers |
3
|
|
|
|
4
|
|
|
.................................................................................................... |
5
|
|
|
MIT License |
6
|
|
|
Copyright (c) 2021-2023 AUT Iran, Mohammad H Forouhesh |
7
|
|
|
Copyright (c) 2021-2022 MetoData.ai, Mohammad H Forouhesh |
8
|
|
|
.................................................................................................... |
9
|
|
|
This module abstracts sklearn classifier. |
10
|
|
|
""" |
11
|
|
|
|
12
|
1 |
|
import os |
13
|
1 |
|
import pickle |
14
|
1 |
|
from .meta_clf import MetaClf |
15
|
|
|
|
16
|
|
|
|
17
|
1 |
View Code Duplication |
class MetaSkLearnClf(MetaClf): |
|
|
|
|
18
|
1 |
|
def __init__(self, classifier_instance, **kwargs): |
19
|
1 |
|
super().__init__(classifier_instance=classifier_instance, **kwargs) |
20
|
1 |
|
if 'load_path' in kwargs and kwargs['load_path'] is not None: self.load_model(kwargs['load_path']) |
|
|
|
|
21
|
|
|
|
22
|
1 |
|
def load_model(self, load_path: str): |
23
|
|
|
""" |
24
|
|
|
A tool to load model from disk. |
25
|
|
|
:param load_path: Model path. |
26
|
|
|
:return: None |
27
|
|
|
""" |
28
|
|
|
|
29
|
1 |
|
loading_prep = lambda string: f'model_dir/{load_path}/{string}' |
30
|
1 |
|
self.emb.load(loading_prep('emb.pkl')) |
31
|
1 |
|
with open(loading_prep('model.pkl'), 'rb') as f: |
|
|
|
|
32
|
1 |
|
self.clf = pickle.load(f) |
33
|
1 |
|
with open(loading_prep('scaler.pkl'), 'rb') as f: |
|
|
|
|
34
|
1 |
|
self.scaler = pickle.load(f) |
35
|
|
|
|
36
|
1 |
|
def save_model(self, save_path: str): |
37
|
|
|
""" |
38
|
|
|
A tool to save model to disk |
39
|
|
|
:param save_path: Saving path. |
40
|
|
|
:return: None. |
41
|
|
|
""" |
42
|
|
|
|
43
|
|
|
os.makedirs(f'model_dir/{save_path}', exist_ok=True) |
44
|
|
|
saving_prep = lambda string: f'model_dir/{save_path}/{string}' |
45
|
|
|
self.emb.save(saving_prep('emb.pkl')) |
46
|
|
|
with open(saving_prep('scaler.pkl'), 'wb') as f: |
|
|
|
|
47
|
|
|
pickle.dump(self.scaler, f, pickle.HIGHEST_PROTOCOL) |
48
|
|
|
with open(saving_prep('model.pkl'), 'wb') as f: |
|
|
|
|
49
|
|
|
pickle.dump(self.clf, f, pickle.HIGHEST_PROTOCOL) |
50
|
|
|
|