钢筋计数模型训练教学与实践 中间内容省略 Epoch:25 epochiter: 30/50 Totel iter 1230 L: 0.3628 C: 0.5933Batch time: 1.1411 sec. LR: 0.01000000 Epoch:25 epochiter: 40/50 Totel iter 1240 L: 0.6436 C: 0.6199Batch time: 1.5384 sec. LR: 0.01000000 training cost 1556.92 s 任务四:模型推理 1.已完成训练,下面开始测试模型,首先需定义目标检测类 输入: cfg VOCConfig imgdim 416 rgbmeans (104, 117, 123) priorbox PriorBox(cfg) with torch.nograd(): priors priorbox.forward() if torch.cuda.isavailable(): priors priors.cuda() class ObjectDetector: """ 定义目标检测类 """ def init(self, net, detection, transform, numclassesnumclasses, thresh0.01, cudaTrue): self.net net self.detection detection self.transform transform self.numclasses numclasses self.thresh thresh self.cuda torch.cuda.isavailable() def predict(self, img): t {'imdetect': Timer(), 'misc': Timer()} scale torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]]) with torch.nograd(): x self.transform(img).unsqueeze(0) if self.cuda: x x.cuda() scale scale.cuda() t['imdetect'].tic() out net(x) forward pass boxes, scores self.detection.forward(out, priors) detecttime t['imdetect'].toc() boxes boxes[0] scores scores[0] scale each detection back up to the image boxes scale boxes boxes.cpu().numpy() scores scores.cpu().numpy() t['misc'].tic() allboxes [[] for in range(numclasses)] for j in range(1, numclasses): inds np.where(scores[:, j] > self.thresh)[0] if len(inds) 0: allboxes[j] np.zeros([0, 5], dtypenp.float32) continue cbboxes boxes[inds] cscores scores[inds, j] cdets np.hstack((cbboxes, cscores[:, np.newaxis])).astype( np.float32, copyFalse) keep nms(cdets, 0.2, forcecpuFalse) cdets cdets[keep, :] allboxes[j] cdets nmstime t['misc'].toc() totaltime detecttime + nmstime return allboxes, totaltime 2.定义推理网络,并加载前面训练的loss最低的模型 输入: trainedmodels os.listdir(os.path.join(ROOTDIR, './rebarcount/modelsnapshots'))