Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

predict_model.py 6.6 KB

You have to be logged in to leave a comment. Sign In
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
  1. import sys
  2. import yaml
  3. import torch
  4. import torch.nn as nn
  5. import json
  6. import os
  7. import numpy as np
  8. import pandas as pd
  9. from tqdm.auto import tqdm
  10. from utils.misc import DETRModel, Logger, sample_metrics, get_data, AverageMeter
  11. from utils.dataset import CustomDataset
  12. import utils.misc as util
  13. import torchvision.transforms as T
  14. '''
  15. Main function of this script. It is explained in more detail in the tutorial.
  16. '''
  17. def run(parameters, directories, ids_dict):
  18. #Retrieving needed directories
  19. csv_path = directories['csv_path']
  20. train_test_path = directories['train_test_path']
  21. test_dir = os.path.join(train_test_path, "test")
  22. output_path = directories['output_path']
  23. test_model = parameters['test_model']
  24. trained_model_file = os.path.join(output_path, f'{test_model}.pth')
  25. detr_path = directories['detr_path']
  26. sys.path.extend([detr_path])
  27. #Retrieving needed parameters
  28. num_classes = parameters['num_classes']
  29. model_name = parameters['model_name']
  30. dev = parameters['dev']
  31. weight_dict = parameters['weight_dict']
  32. null_class_coef = parameters['null_class_coef']
  33. pre_trained = parameters['pre_trained']
  34. from_scratch = parameters['from_scratch']
  35. device = torch.device(dev)
  36. if pre_trained or from_scratch:
  37. num_queries = parameters['num_queries']
  38. #Importing classes that are required from DETR's repository
  39. from models.detr import DETR,SetCriterion
  40. from models.backbone import Backbone,Joiner
  41. from models.position_encoding import PositionEmbeddingSine
  42. from models.transformer import Transformer
  43. #Creating empty model in the case of being pre-trained or being trained from scratch
  44. #because some parameters might be different from the one that is on DETR's repository
  45. hidden_dim = 256
  46. backbone = Backbone(model_name, train_backbone=True, return_interm_layers=False, dilation=True)
  47. pos_enc = PositionEmbeddingSine(hidden_dim // 2, normalize=True)
  48. backbone_with_pos_enc = Joiner(backbone, pos_enc)
  49. backbone_with_pos_enc.num_channels = backbone.num_channels
  50. transformer = Transformer(d_model=hidden_dim, return_intermediate_dec=True)
  51. model = DETR(backbone_with_pos_enc, transformer, num_classes=num_classes, num_queries=num_queries, aux_loss=False)
  52. else:
  53. #Initializing a model with the characteristics of that from DETR's repository
  54. model = DETRModel(model_name=model_name, num_classes=num_classes)
  55. #Loading the fine-tuned or trained models
  56. try:
  57. model.load_state_dict(torch.load(trained_model_file, map_location=torch.device('cpu')))
  58. model.to(device)
  59. model.eval()
  60. except IOError as e:
  61. print("I/O error{}: {}".format(e.errno, e.strerror))
  62. #Creation of the loss function
  63. cost_bbox = weight_dict['loss_bbox']
  64. cost_giou = weight_dict['loss_giou']
  65. cost_class = weight_dict['loss_ce']
  66. from models.matcher import HungarianMatcher
  67. from models.detr import SetCriterion
  68. matcher = HungarianMatcher(cost_class=cost_class, cost_bbox=cost_bbox, cost_giou=cost_giou)
  69. losses = ['labels', 'boxes', 'cardinality']
  70. criterion = SetCriterion(num_classes,
  71. matcher, weight_dict,
  72. eos_coef=null_class_coef,
  73. losses=losses)
  74. criterion = criterion.to(device)
  75. criterion.eval()
  76. #Retrieving information about the images in the test set
  77. train_ids, val_ids, test_ids = ids_dict.values()
  78. test_csv = os.path.join(csv_path, 'test.csv')
  79. test_marking = pd.read_csv(test_csv)
  80. test_image_data = test_marking.groupby('image_id')
  81. test_info = [get_data(img_id, test_image_data) for img_id in test_ids]
  82. null_test_images = [x['image_id'] for x in test_info if len(x['boxes'])==0]
  83. print(f'Total number of images in test set: {len(test_info)}')
  84. print('Images with no boxes in test set: ', len(null_test_images))
  85. null_test_boxes = np.zeros(num_classes)
  86. for img_id in test_info:
  87. for i in range(len(img_id['boxes'])):
  88. null_test_boxes[img_id['labels'][i]] += 1
  89. #Creating test dataset
  90. test_ds = CustomDataset(test_info, test_dir, image_set = 'test')
  91. size = len(test_ds)
  92. logger = util.Logger('test_metrics', format='json')
  93. log = None
  94. bar = tqdm(test_ds, total=size, leave=False)
  95. #Iterating through the images in test set to compute the metrics
  96. for i, (img, target) in enumerate(bar):
  97. img = img.unsqueeze(0)
  98. img = img.to(device)
  99. target = {k: v.to(device) for k, v in target.items()}
  100. output = model(img)
  101. loss_dict = criterion(output, [target])
  102. if log is None:
  103. log = {k:AverageMeter() for k in loss_dict}
  104. log['total_loss'] = AverageMeter()
  105. for i in range(len(null_test_boxes)):
  106. log[f'avg_prec_{i}'] = AverageMeter(id=i)
  107. log[f'avg_rec_{i}'] = AverageMeter(id=i)
  108. log[f'avg_f1_{i}'] = AverageMeter(id=i)
  109. for k,v in loss_dict.items():
  110. log[k].update(v.item())
  111. total_loss = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)
  112. log['total_loss'].update(total_loss.item())
  113. metrics = sample_metrics(output, [target])
  114. for i in range(len(null_test_boxes)):
  115. class_metric = metrics[:, i]
  116. log[f'avg_prec_{i}'].update(class_metric[0])
  117. log[f'avg_rec_{i}'].update(class_metric[1])
  118. log[f'avg_f1_{i}'].update(class_metric[2])
  119. bar.set_postfix({k:v.avg(null_test_boxes) for k,v in log.items() if v.id is None})
  120. log = {k:v.avg(null_test_boxes) for k,v in log.items()}
  121. logger.save(log)
  122. for k,v in log.items():
  123. print(k, v)
  124. if __name__ == "__main__":
  125. #Attempting to read dir.yaml file that contains directories information
  126. try:
  127. with open(os.path.join("configs","dir.yaml"), "r") as fp:
  128. directories = yaml.load(fp, Loader=yaml.FullLoader)
  129. except:
  130. sys.exit('File dir.yaml could not be read.')
  131. #Attempting to read parameters.yaml file that contains parameters information
  132. try:
  133. with open(os.path.join("configs","parameters.yaml"), "r") as fp:
  134. parameters = yaml.load(fp, Loader=yaml.FullLoader)
  135. except:
  136. sys.exit('File parameters.yaml could not be read.')
  137. #Attempting to read ids_dict.json file that contains sets' images ids
  138. try:
  139. with open("ids_dict.json", "r") as fp:
  140. ids_dict = json.load(fp)
  141. except:
  142. sys.exit('File ids_dict.json could not be read.')
  143. run(parameters, directories, ids_dict)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...