-
Notifications
You must be signed in to change notification settings - Fork 0
/
model_utls.py
56 lines (44 loc) · 1.62 KB
/
model_utls.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
import torch
# ------------------------------------------------------------------------------
# Base model class
# ------------------------------------------------------------------------------
class _Model(torch.nn.Module):
"""
Base class for all models
"""
def __init__(self):
super(_Model, self).__init__()
@classmethod
def from_config(cls, config: dict):
""" All models should have this class method """
raise NotImplementedError
# ------------------------------------------------------------------------------
# Helper class to load models more easily
# ------------------------------------------------------------------------------
class ModelLoader:
"""
Helper class used to instantiate the desired model from a string
"""
@staticmethod
def get_model(model_name):
"""
Returns an instance of the desired model
:param model_name: the model name as a string (insensitive to snake_case
or UpperCamelCase)
"""
resolved_name = ModelLoader._resolve_name(model_name)
for subclass in _Model.__subclasses__():
if subclass.__name__ == resolved_name:
return subclass
raise NameError(
"The model name {} was not found.".format(resolved_name))
@staticmethod
def _resolve_name(name: str):
"""
Converts all snake_case names to UpperCamelCase and does nothing if name
is already in the right case
"""
components = name.split('_')
if len(components) > 1:
return ''.join(x.title() for x in components)
return name