遂昌网站建设,开发一款app软件需要多久,普洱市网站建设,怎么给WordPress打卡计数提示#xff1a;文章写完后#xff0c;目录可以自动生成#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、val.py的大致结构如下#xff1a;1.0 准备工作1.获取文件路径2.存储预测信息为.txt文件3.存储预测信息为coco格式的.json文件 1.1 主函数main#xff1a;… 提示文章写完后目录可以自动生成如何生成可参考右边的帮助文档 文章目录 前言一、val.py的大致结构如下1.0 准备工作1.获取文件路径2.存储预测信息为.txt文件3.存储预测信息为coco格式的.json文件 1.1 主函数main解析命令行参数调用run函数1.2 run函数①传参②模型的初始化和设备设置以及加载模型和数据③模型设置为评估模式、CUDA加速、数据集类型、类别数以及用于计算mAP的IoU向量④数据加载器的设置和模型评估⑤计算指标、打印结果、打印处理速度⑥绘制图表、保存JSON文件以及返回评估结果 总结run函数 二、训练train、验证val、推理detcet三文件的关系1.三文件的作用2.三者的关系①数据集分为train训练用数据集\val验证用数据集\test测试用数据集,即训练集、验证集、测试集②train是第一步在每一轮epoch训练结束后都会用val去验证当前模型的mAP、混淆矩阵等指标以及各个超参数是否是最佳得到一个best模型后再用detcet去实际应用。②在评估模型结果时候使用train训练出来的最好的模型best.pt去运行val.py这个得到的结果能用来当论文最终评价指标而实际做应用做检测任务用testdetcet来做。 前言
一、val.py的大致结构如下
def save_one_txt(predn, save_conf, shape, file):# save txtdef save_one_json(predn, jdict, path, class_map):# Save one JSON result {image_id: 42, # category_id: 18, # bbox: [258.15, 41.29, 348.26, 243.78], # score: 0.236}def process_batch(detections, labels, iouv):Return correct predictions matrix. Both sets of boxes are in (x1, y1, x2, y2) format.Arguments:detections (Array[N, 6]), x1, y1, x2, y2, conf, classlabels (Array[M, 5]), class, x1, y1, x2, y2Returns:correct (Array[N, 10]), for 10 IoU levels# 计算指标的关键函数之一# iou[0.5:0.95]10个不同的iou阈值下计算标签与预测的匹配结果存于矩阵标记是否预测正确torch.no_grad()
def run(data,weightsNone, # model.pt path(s)batch_size32, # batch sizeimgsz640, # inference size (pixels)conf_thres0.001, # confidence thresholdiou_thres0.6, # NMS IoU thresholdtaskval, # train, val, test, speed or studydevice, # cuda device, i.e. 0 or 0,1,2,3 or cpuworkers8, # max dataloader workers (per RANK in DDP mode)......
):# 函数run()的处理流程如下1. 加载模型2. 加载数据3. 网络预测NMS处理4. 计算APmAP5. 绘制指标图6. 保存结果def parse_opt():# 运行相关参数定义def main(opt):# 入口函数run(**vars(opt))if __name__ __main__:opt parse_opt()main(opt)
1.0 准备工作
1.获取文件路径
FILE Path(__file__).resolve() #获取当前文件的绝对路径D://yolov5/val.py
ROOT FILE.parents[0] # YOLOv5 root directory当前文件的父目录上一级目录D://yolov5/
if str(ROOT) not in sys.path:sys.path.append(str(ROOT)) # add ROOT to PATH把root添加到运行路径
ROOT Path(os.path.relpath(ROOT, Path.cwd())) # relative将root设置为相对路径2.存储预测信息为.txt文件
def save_one_txt(predn, save_conf, shape, file):# Save one txt resultgn torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwhgn [w, h, w, h] 对应图片的宽高 用于后面归一化for *xyxy, conf, cls in predn.tolist():# tolist变为列表xywh (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh将左上角和右下角的xyxy格式转为xywh(中心点位置宽高)格式并归一化转化为列表再保存line (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format若save_conf为true则line的形式是类别 xywh 置信度否则line的形式是 类别 xywhwith open(file, a) as f:f.write((%g * len(line)).rstrip() % line \n) # 写入对应的文件夹里路径默认为“runs\detect\exp*\labels”3.存储预测信息为coco格式的.json文件
def save_one_json(predn, jdict, path, class_map):# Save one JSON result {image_id: 42, category_id: 18, bbox: [258.15, 41.29, 348.26, 243.78], score: 0.236}image_id int(path.stem) if path.stem.isnumeric() else path.stem#获取图片IDbox xyxy2xywh(predn[:, :4]) # xywh转换为中心点坐标和宽、高的形式box[:, :2] - box[:, 2:] / 2 # xy center to top-left cornerfor p, b in zip(predn.tolist(), box.tolist()):jdict.append({image_id: image_id, #图片IDcategory_id: class_map[int(p[5])], #类别bbox: [round(x, 3) for x in b], #预测框位置score: round(p[4], 5)}) #预测得分注意之前的的xyxy格式是左上角右下角坐标 xywh是中心的坐标和宽高而coco的json格式的框坐标是xywh(左上角坐标 宽高)所以 box[:, :2] - box[:, 2:] / 2 这行代码是将中心点坐标 - 左上角坐标 zip每次从predn.tolist()和box.tolist()里各拿一个组成新的元组分别赋值给pb
1.1 主函数main解析命令行参数调用run函数
不用多说了训练、验证、推理都是这样的结构。
1.2 run函数
①传参
def run(data,weightsNone, # model.pt path(s)batch_size32, # batch sizeimgsz640, # inference size (pixels)conf_thres0.001, # confidence thresholdiou_thres0.6, # NMS IoU thresholdmax_det300, # maximum detections per imagetaskval, # train, val, test, speed or studydevice, # cuda device, i.e. 0 or 0,1,2,3 or cpuworkers8, # max dataloader workers (per RANK in DDP mode)single_clsFalse, # treat as single-class datasetaugmentFalse, # augmented inferenceverboseFalse, # verbose outputsave_txtFalse, # save results to *.txtsave_hybridFalse, # save labelprediction hybrid results to *.txtsave_confFalse, # save confidences in --save-txt labelssave_jsonFalse, # save a COCO-JSON results fileprojectROOT / runs/val, # save to project/namenameexp, # save to project/nameexist_okFalse, # existing project/name ok, do not incrementhalfTrue, # use FP16 half-precision inferencednnFalse, # use OpenCV DNN for ONNX inferencemodelNone,dataloaderNone,save_dirPath(),plotsTrue,callbacksCallbacks(),compute_lossNone,
):②模型的初始化和设备设置以及加载模型和数据
# Initialize/load model and set devicetraining model is not Noneif training: # called by train.pydevice, pt, jit, engine next(model.parameters()).device, True, False, False # get model device, PyTorch modelhalf device.type ! cpu # half precision only supported on CUDAmodel.half() if half else model.float()else: # called directlydevice select_device(device, batch_sizebatch_size)# Directoriessave_dir increment_path(Path(project) / name, exist_okexist_ok) # increment run(save_dir / labels if save_txt else save_dir).mkdir(parentsTrue, exist_okTrue) # make dir# Load modelmodel DetectMultiBackend(weights, devicedevice, dnndnn, datadata, fp16half)stride, pt, jit, engine model.stride, model.pt, model.jit, model.engineimgsz check_img_size(imgsz, sstride) # check image sizehalf model.fp16 # FP16 supported on limited backends with CUDAif engine:batch_size model.batch_sizeelse:device model.deviceif not (pt or jit):batch_size 1 # export.py models default to batch-size 1LOGGER.info(fForcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models)# Datadata check_dataset(data) # check③模型设置为评估模式、CUDA加速、数据集类型、类别数以及用于计算mAP的IoU向量
# Configuremodel.eval()cuda device.type ! cpuis_coco isinstance(data.get(val), str) and data[val].endswith(fcoco{os.sep}val2017.txt) # COCO datasetnc 1 if single_cls else int(data[nc]) # number of classesiouv torch.linspace(0.5, 0.95, 10, devicedevice) # iou vector for mAP0.5:0.95niou iouv.numel()④数据加载器的设置和模型评估
数据加载器设置 如果不是训练模式则进行一系列设置包括检查权重是否在相同数据集上训练、模型预热、设置推理时的填充和矩形参数等。 确定任务类型为训练、验证或测试并创建数据加载器。评估过程 初始化一些变量如混淆矩阵、类别名称、类别映射等。 针对数据加载器中的每个批次进行评估操作包括数据准备、推理、损失计算、非极大值抑制、指标计算等。 根据预测结果和标签计算指标如准确率、召回率、mAP等。 根据需要保存结果到文本文件或JSON文件并进行可视化绘图。 在评估过程中运行回调函数用于处理评估过程中的特定事件。
# Dataloaderif not training:if pt and not single_cls: # check --weights are trained on --datancm model.model.ncassert ncm nc, (f{weights} ({ncm} classes) trained on different --data than what you passed ({nc} fclasses). Pass correct combination of --weights and --data that are trained together.)model.warmup(imgsz(1 if pt else batch_size, 3, imgsz, imgsz)) # warmuppad, rect (0.0, False) if task speed else (0.5, pt) # square inference for benchmarkstask task if task in (train, val, test) else val # path to train/val/test imagesdataloader create_dataloader(data[task],imgsz,batch_size,stride,single_cls,padpad,rectrect,workersworkers,prefixcolorstr(f{task}: ),)[0]seen 0confusion_matrix ConfusionMatrix(ncnc)names model.names if hasattr(model, names) else model.module.names # get class namesif isinstance(names, (list, tuple)): # old formatnames dict(enumerate(names))class_map coco80_to_coco91_class() if is_coco else list(range(1000))s (%22s %11s * 6) % (Class, Images, Instances, P, R, mAP50, mAP50-95)tp, fp, p, r, f1, mp, mr, map50, ap50, map 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0dt Profile(devicedevice), Profile(devicedevice), Profile(devicedevice) # profiling timesloss torch.zeros(3, devicedevice)jdict, stats, ap, ap_class [], [], [], []callbacks.run(on_val_start)pbar tqdm(dataloader, descs, bar_formatTQDM_BAR_FORMAT) # progress barfor batch_i, (im, targets, paths, shapes) in enumerate(pbar):callbacks.run(on_val_batch_start)with dt[0]:if cuda:im im.to(device, non_blockingTrue)targets targets.to(device)im im.half() if half else im.float() # uint8 to fp16/32im / 255 # 0 - 255 to 0.0 - 1.0nb, _, height, width im.shape # batch size, channels, height, width# Inferencewith dt[1]:preds, train_out model(im) if compute_loss else (model(im, augmentaugment), None)# Lossif compute_loss:loss compute_loss(train_out, targets)[1] # box, obj, cls# NMStargets[:, 2:] * torch.tensor((width, height, width, height), devicedevice) # to pixelslb [targets[targets[:, 0] i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabellingwith dt[2]:preds non_max_suppression(preds, conf_thres, iou_thres, labelslb, multi_labelTrue, agnosticsingle_cls, max_detmax_det)# Metricsfor si, pred in enumerate(preds):labels targets[targets[:, 0] si, 1:]nl, npr labels.shape[0], pred.shape[0] # number of labels, predictionspath, shape Path(paths[si]), shapes[si][0]correct torch.zeros(npr, niou, dtypetorch.bool, devicedevice) # initseen 1if npr 0:if nl:stats.append((correct, *torch.zeros((2, 0), devicedevice), labels[:, 0]))if plots:confusion_matrix.process_batch(detectionsNone, labelslabels[:, 0])continue# Predictionsif single_cls:pred[:, 5] 0predn pred.clone()scale_boxes(im[si].shape[1:], predn[:, :4], shape, shapes[si][1]) # native-space pred# Evaluateif nl:tbox xywh2xyxy(labels[:, 1:5]) # target boxesscale_boxes(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labelslabelsn torch.cat((labels[:, 0:1], tbox), 1) # native-space labelscorrect process_batch(predn, labelsn, iouv)if plots:confusion_matrix.process_batch(predn, labelsn)stats.append((correct, pred[:, 4], pred[:, 5], labels[:, 0])) # (correct, conf, pcls, tcls)# Save/logif save_txt:(save_dir / labels).mkdir(parentsTrue, exist_okTrue)save_one_txt(predn, save_conf, shape, filesave_dir / labels / f{path.stem}.txt)if save_json:save_one_json(predn, jdict, path, class_map) # append to COCO-JSON dictionarycallbacks.run(on_val_image_end, pred, predn, path, names, im[si])# Plot imagesif plots and batch_i 3:plot_images(im, targets, paths, save_dir / fval_batch{batch_i}_labels.jpg, names) # labelsplot_images(im, output_to_target(preds), paths, save_dir / fval_batch{batch_i}_pred.jpg, names) # predcallbacks.run(on_val_batch_end, batch_i, im, targets, paths, shapes, preds)⑤计算指标、打印结果、打印处理速度
计算指标 将统计数据转换为NumPy数组stats [torch.cat(x, 0).cpu().numpy() for x in zip(*stats)]。 根据统计数据计算各类别的准确率、召回率、F1分数、AP等指标tp, fp, p, r, f1, ap, ap_class ap_per_class(*stats, plotplots, save_dirsave_dir, namesnames)。 计算平均准确率、召回率、mAP等指标。打印结果 统计每个类别的目标数量nt np.bincount(stats[3].astype(int), minlengthnc)。 打印整体结果和每个类别的结果包括目标数量、准确率、召回率、AP等指标。 如果没有找到标签则打印警告信息。打印速度 计算预处理、推理和NMS的速度并打印每个图像的处理时间。
# Compute metricsstats [torch.cat(x, 0).cpu().numpy() for x in zip(*stats)] # to numpyif len(stats) and stats[0].any():tp, fp, p, r, f1, ap, ap_class ap_per_class(*stats, plotplots, save_dirsave_dir, namesnames)ap50, ap ap[:, 0], ap.mean(1) # AP0.5, AP0.5:0.95mp, mr, map50, map p.mean(), r.mean(), ap50.mean(), ap.mean()nt np.bincount(stats[3].astype(int), minlengthnc) # number of targets per class# Print resultspf %22s %11i * 2 %11.3g * 4 # print formatLOGGER.info(pf % (all, seen, nt.sum(), mp, mr, map50, map))if nt.sum() 0:LOGGER.warning(fWARNING ⚠️ no labels found in {task} set, can not compute metrics without labels)# Print results per classif (verbose or (nc 50 and not training)) and nc 1 and len(stats):for i, c in enumerate(ap_class):LOGGER.info(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i]))# Print speedst tuple(x.t / seen * 1e3 for x in dt) # speeds per imageif not training:shape (batch_size, 3, imgsz, imgsz)LOGGER.info(fSpeed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape} % t)⑥绘制图表、保存JSON文件以及返回评估结果
绘制图表 如果需要绘制图表plotsTrue则绘制混淆矩阵图表并运行评估结束时的回调函数。保存JSON文件 如果需要保存JSON文件且存在预测结果save_jsonTrue and len(jdict)则保存预测结果到JSON文件中。 使用pycocotools库进行COCO数据集的评估计算mAP和mAP0.5并打印评估结果。返回结果 将模型转换为浮点数格式model.float()。 如果不是训练模式则返回结果包括平均准确率、平均召回率、mAP0.5、mAP等指标每个类别的mAP值以及处理速度。
# Plotsif plots:confusion_matrix.plot(save_dirsave_dir, nameslist(names.values()))callbacks.run(on_val_end, nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix)# Save JSONif save_json and len(jdict):w Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else # weightsanno_json str(Path(../datasets/coco/annotations/instances_val2017.json)) # annotationsif not os.path.exists(anno_json):anno_json os.path.join(data[path], annotations, instances_val2017.json)pred_json str(save_dir / f{w}_predictions.json) # predictionsLOGGER.info(f\nEvaluating pycocotools mAP... saving {pred_json}...)with open(pred_json, w) as f:json.dump(jdict, f)try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynbcheck_requirements(pycocotools2.0.6)from pycocotools.coco import COCOfrom pycocotools.cocoeval import COCOevalanno COCO(anno_json) # init annotations apipred anno.loadRes(pred_json) # init predictions apieval COCOeval(anno, pred, bbox)if is_coco:eval.params.imgIds [int(Path(x).stem) for x in dataloader.dataset.im_files] # image IDs to evaluateeval.evaluate()eval.accumulate()eval.summarize()map, map50 eval.stats[:2] # update results (mAP0.5:0.95, mAP0.5)except Exception as e:LOGGER.info(fpycocotools unable to run: {e})# Return resultsmodel.float() # for trainingif not training:s f\n{len(list(save_dir.glob(labels/*.txt)))} labels saved to {save_dir / labels} if save_txt else LOGGER.info(fResults saved to {colorstr(bold, save_dir)}{s})maps np.zeros(nc) mapfor i, c in enumerate(ap_class):maps[c] ap[i]return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t总结run函数
这个run函数主要完成了模型在验证集上的评估过程包括以下几个关键步骤
数据加载器设置根据验证集数据设置数据加载器准备进行模型评估。 模型评估过程对每个批次的数据进行推理、损失计算、非极大值抑制、指标计算等操作生成评估统计数据。 计算评估指标根据统计数据计算各类别的准确率、召回率、mAP等指标并打印结果。 绘制图表和保存结果根据需要绘制混淆矩阵图表保存预测结果到JSON文件并进行COCO数据集的评估。 返回结果将评估结果返回包括平均准确率、平均召回率、mAP0.5、mAP等指标每个类别的mAP值以及处理速度。
二、训练train、验证val、推理detcet三文件的关系
1.三文件的作用
训练training文件主要负责模型的训练过程包括加载数据集、定义模型架构、设置损失函数、选择优化器、迭代训练数据、更新模型参数等操作。训练文件用于训练模型以提高其性能和泛化能力通常包括多个训练周期epochs和批次batches的训练过程。
验证validation文件主要负责在训练过程中对模型进行验证和评估通常包括加载验证数据集、使用训练好的模型进行评估、计算指标、绘制图表、保存结果等操作。验证文件用于评估模型在独立验证集上的性能表现帮助调整模型超参数、防止过拟合等。
推理detcet文件主要负责使用训练好的模型对新的数据进行预测和推断通常包括加载模型权重、准备输入数据、进行前向传播推理、解析输出结果、可视化结果等操作。推理文件用于模型在实际应用中的使用例如对图像、文本或其他数据进行分类、检测、生成等任务。
2.三者的关系
①数据集分为train训练用数据集\val验证用数据集\test测试用数据集,即训练集、验证集、测试集
②train是第一步在每一轮epoch训练结束后都会用val去验证当前模型的mAP、混淆矩阵等指标以及各个超参数是否是最佳得到一个best模型后再用detcet去实际应用。
②在评估模型结果时候使用train训练出来的最好的模型best.pt去运行val.py这个得到的结果能用来当论文最终评价指标而实际做应用做检测任务用testdetcet来做。