-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpredict.py
60 lines (50 loc) · 1.86 KB
/
predict.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
import argparse
from classifier import ImageClassifier
from dataprocessing import process_image
import json
import numpy as np
import torch
def main():
"""
Set up arguments to be used for inference
"""
parser = argparse.ArgumentParser(description='Trains a new network on a dataset and save the model as a checkpoint.')
parser.add_argument('image_path',
type=str,
help='Image file')
parser.add_argument('checkoint',
type=str,
help='Checkpoint file')
parser.add_argument('--top_k',
dest='top_k',
metavar='T',
type=int,
default=1,
help='Top K most likely classes')
parser.add_argument('--category_names',
dest='category_names',
metavar='C',
type=str,
default='cat_to_name.json',
help='Mapping of categories to real names')
parser.add_argument('--gpu',
dest='gpu',
type=bool,
nargs='?',
default=False,
const=True,
help='Use GPU for inference')
args = parser.parse_args()
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') if args.gpu else 'cpu'
# load category mapping
with open(args.category_names, 'r') as f:
cat_to_name = json.load(f)
# load the model
model = ImageClassifier(device)
model.load(args.checkoint)
# predict
predictions = model.predict(process_image(args.image_path), args.top_k, cat_to_name)
for name, prob in predictions:
print(f'{name}: {prob:.2f}%')
if __name__ == '__main__':
main()