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

Function main

CV/Pytorch_classification/DenseNet/predict.py:11–55  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

9from model import densenet121
10
11def main():
12 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
13
14 data_transform = transforms.Compose([
15 transforms.Resize(256),
16 transforms.CenterCrop(224),
17 transforms.ToTensor(),
18 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
19 ])
20
21 # load image
22 img_path = ''
23 assert os.path.exists(img_path), "file: '{}' does not exist.".format(img_path)
24 img = Image.open(img_path)
25 plt.imshow(img)
26 # [N, C, H, W]
27 img = data_transform(img)
28 # expand batch dimension
29 img = torch.unsqueeze(img, dim=0)
30
31 # read class_indict
32 json_path = ''
33 assert os.path.exists(json_path), "file: '{}' does not exist.".format(json_path)
34
35 with open(json_path, "r") as f:
36 class_indict = json.load(f)
37
38 # create model
39 model = densenet121(num_classes=5).to(device)
40 # load model weights
41 model_weight_path = "./weights/model-3.pth"
42 model.load_state_dict(torch.load(model_weight_path, map_location=device))
43 model.eval()
44 with torch.no_grad():
45 # predict class
46 output = torch.squezze(model(img.to(device)).cpu())
47 predict = torch.softmax(output, dim=0)
48 predict_cla = torch.argmax(predict).numpy()
49
50 print_res = "class:{} prob:{:.3}".format(class_indict[str(predict_cla)], predict[predict_cla].numpy())
51 plt.title(print_res)
52 for i in range(len(predict)):
53 print("class:{:.10} prob:{:.3}".format(class_indict[str(predict_cla)], predict[i].numpy()))
54
55 plt.show()
56
57if __name__ == '__main__':
58 main()

Callers 1

predict.pyFile · 0.70

Calls 1

densenet121Function · 0.90

Tested by

no test coverage detected