forked from ryderling/DEEPSEC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_module.py
48 lines (38 loc) · 1.27 KB
/
basic_module.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# **************************************
# @Time : 2018/10/12 14:14
# @Author : Xiang Ling
# @Lab : nesa.zju.edu.cn
# @File : basic_module.py
# **************************************
import torch
class BasicModule(torch.nn.Module):
"""
encapsulate the nn.Module to providing both load and save functions
"""
def __init__(self):
super(BasicModule, self).__init__()
self.model_name = str(type(self))
# load the model
def load(self, path, device):
"""
:param path:
:param device:
:return:
"""
print('starting to LOAD the ${}$ Model from {} within the {} device'.format(self.model_name, path, device))
if device == torch.device('cpu'):
self.load_state_dict(torch.load(path, map_location='cpu'))
else:
self.load_state_dict(torch.load(path))
# save the model
def save(self, name=None):
"""
:param name:
:return:
"""
assert name is not None, 'please specify the path name to save the module'
with open(name, 'wb') as file:
torch.save(self.state_dict(), file)
print('starting to SAVE the ${}$ Model to ${}$\n'.format(self.model_name, name))