MCPcopy Create free account
hub / github.com/Sirwenhao/Deep-Learning-Notes / main

Function main

CV/Pytorch_classification/EfficientNet/predict.py:13–66  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

11from model import efficientnet_b0 as create_model
12
13def main():
14 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
15
16 img_size = {"B0": 224,
17 "B1": 240,
18 "B2": 260,
19 "B3": 300,
20 "B4": 380,
21 "B5": 456,
22 "B6": 528,
23 "B7": 600}
24 num_model = 'B0'
25
26 data_transform = transforms.Compose(
27 [transforms.Resize(img_size[num_model]),
28 transforms.CenterCrop(img_size[num_model]),
29 transforms.CenterCrop(img_size[num_model]),
30 transforms.ToTensor(),
31 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
32
33 # load image
34 img_path = r''
35 assert os.path.exists(img_path). "file: '{}' does not exist.".format(img_path)
36 img = Image.open(img_path)
37 plt.show(img)
38 # [N, C, H, W]
39 img = data_transform(img)
40 # expand batch dimension
41 img = torch.unsqueeze(img, dim=0)
42
43 # read class_indict
44 json_path = r''
45 assert os.path.exists(json_path), "file: '{}' does not exist.".format(json_path)
46
47 with open(json_path, 'r') as f:
48 class_indict = json.load(f)
49
50 # create model
51 model = create_model(num_classes=5).to(device)
52 # load model weights
53 model_weight_path = r""
54 model.load_state_dict(torch.load(model_weight_path, map_location=device))
55 model.eval()
56 with torch.no_grad():
57 # predict class
58 output = torch.squeeze(model(img.to(device))).cpu()
59 predict = torch.softmax(output, dim=0)
60 predict_cla = torch.argmax(predict).numpy()
61
62 print_res = "class: {:10} prob:{:.3}".format(class_indict[str(predict_cla)], predict[predict_cla].numpy())
63 plt.title(print_res)
64 for i in range(len(predict)):
65 print("class: {:10} prob:{:.3}".format(class_indict[str(i)], predict[i].numpy()))
66 plt.show()
67
68if __name__ == '__main__':
69 main()

Callers 1

predict.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected