-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.py
58 lines (52 loc) · 2.11 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
# Copyright 2021 Zhongyang Zhang
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from pathlib2 import Path
def load_model_path(root=None, version=None, v_num=None, best=False):
""" When best = True, return the best model's path in a directory
by selecting the best model with largest epoch. If not, return
the last model saved. You must provide at least one of the
first three args.
Args:
root: The root directory of checkpoints. It can also be a
model ckpt file. Then the function will return it.
version: The name of the version you are going to load.
v_num: The version's number that you are going to load.
best: Whether return the best model.
"""
def sort_by_epoch(path):
name = path.stem
epoch=int(name.split('-')[1].split('=')[1])
return epoch
def generate_root():
if root is not None:
return root
elif version is not None:
return str(Path('lightning_logs', version, 'checkpoints'))
else:
return str(Path('lightning_logs', f'version_{v_num}', 'checkpoints'))
if root==version==v_num==None:
return None
root = generate_root()
if Path(root).is_file():
return root
if best:
files=[i for i in list(Path(root).iterdir()) if i.stem.startswith('best')]
files.sort(key=sort_by_epoch, reverse=True)
res = str(files[0])
else:
res = str(Path(root) / 'last.ckpt')
return res
def load_model_path_by_args(args):
return load_model_path(root=args.load_dir, version=args.load_ver, v_num=args.load_v_num)