YOLOv5复现时,utils下py文件未成功引用

在复现YOLOv5模型时,可能会出现utils文件夹下的general.py、loggers.py等引用错误,下面标红,是路径的问题,可以在loggers文件夹下找到一个__init__.py文件(注意init前面和后面都是两个下划线),在里面加上下段代码即可

import sys
from pathlib import Path
sys.path.append('..')
sys.path.append(str(Path(__file__).parent.parent.parent))

完整的loggers文件夹下的__init__.py文件如下:

# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Logging utils
"""

import warnings
from threading import Thread

import torch
from tensorboardX import SummaryWriter
import sys
from pathlib import Path
sys.path.append('..')
sys.path.append(str(Path(__file__).parent.parent.parent))  # add utils/ to path
# FILE = Path(__file__).resolve()
# ROOT = FILE.parents[1]

from utils.general import colorstr, emojis
from utils.loggers.wandb.wandb_utils import WandbLogger
from utils.plots import plot_images, plot_results
from utils.torch_utils import de_parallel

LOGGERS = ('csv', 'tb', 'wandb')  # text-file, TensorBoard, Weights & Biases

try:
    import wandb

    assert hasattr(wandb, '__version__')  # verify package import not local dir
except (ImportError, AssertionError):
    wandb = None


class Loggers():
    # YOLOv5 Loggers class
    def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):
        self.save_dir = save_dir
        self.weights = weights
        self.opt = opt
        self.hyp = hyp
        self.logger = logger  # for printing results to console
        self.include = include
        self.keys = ['train/box_loss', 'train/obj_loss', 'train/cls_loss',  # train loss
                     'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',  # metrics
                     'val/box_loss', 'val/obj_loss', 'val/cls_loss',  # val loss
                     'x/lr0', 'x/lr1', 'x/lr2']  # params
        for k in LOGGERS:
            setattr(self, k, None)  # init empty logger dictionary
        self.csv = True  # always log to csv

        # Message
        if not wandb:
            prefix = colorstr('Weights & Biases: ')
            s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)"
            print(emojis(s))

        # TensorBoard
        s = self.save_dir
        if 'tb' in self.include and not self.opt.evolve:
            prefix = colorstr('TensorBoard: ')
            self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/")
            self.tb = SummaryWriter(str(s))

        # W&B
        if wandb and 'wandb' in self.include:
            wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://')
            run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None
            self.opt.hyp = self.hyp  # add hyperparameters
            self.wandb = WandbLogger(self.opt, run_id)
        else:
            self.wandb = None

    def on_pretrain_routine_end(self):
        # Callback runs on pre-train routine end
        paths = self.save_dir.glob('*labels*.jpg')  # training labels
        if self.wandb:
            self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]})

    def on_train_batch_end(self, ni, model, imgs, targets, paths, plots, sync_bn):
        # Callback runs on train batch end
        if plots:
            if ni == 0:
                if not sync_bn:  # tb.add_graph() --sync known issue https://github.com/ultralytics/yolov5/issues/3754
                    with warnings.catch_warnings():
                        warnings.simplefilter('ignore')  # suppress jit trace warning
                        self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), [])
            if ni < 3:
                f = self.save_dir / f'train_batch{ni}.jpg'  # filename
                Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
            if self.wandb and ni == 10:
                files = sorted(self.save_dir.glob('train*.jpg'))
                self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})

    def on_train_epoch_end(self, epoch):
        # Callback runs on train epoch end
        if self.wandb:
            self.wandb.current_epoch = epoch + 1

    def on_val_image_end(self, pred, predn, path, names, im):
        # Callback runs on val image end
        if self.wandb:
            self.wandb.val_one_image(pred, predn, path, names, im)

    def on_val_end(self):
        # Callback runs on val end
        if self.wandb:
            files = sorted(self.save_dir.glob('val*.jpg'))
            self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]})

    def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
        # Callback runs at the end of each fit (train+val) epoch
        x = {k: v for k, v in zip(self.keys, vals)}  # dict
        if self.csv:
            file = self.save_dir / 'results.csv'
            n = len(x) + 1  # number of cols
            s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n')  # add header
            with open(file, 'a') as f:
                f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n')

        if self.tb:
            for k, v in x.items():
                self.tb.add_scalar(k, v, epoch)

        if self.wandb:
            self.wandb.log(x)
            self.wandb.end_epoch(best_result=best_fitness == fi)

    def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
        # Callback runs on model save event
        if self.wandb:
            if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1:
                self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)

    def on_train_end(self, last, best, plots, epoch):
        # Callback runs on training end
        if plots:
            plot_results(file=self.save_dir / 'results.csv')  # save results.png
        files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]]
        files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()]  # filter

        if self.tb:
            import cv2
            for f in files:
                self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')

        if self.wandb:
            self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]})
            # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model
            if not self.opt.evolve:
                wandb.log_artifact(str(best if best.exists() else last), type='model',
                                   name='run_' + self.wandb.wandb_run.id + '_model',
                                   aliases=['latest', 'best', 'stripped'])
                self.wandb.finish_run()
            else:
                self.wandb.finish_run()
                self.wandb = WandbLogger(self.opt)

如果依旧报错,就在utils文件夹下面创建空白的__init__.py文件,将目录的总目录设置成根目录。

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 你好,感谢你的介绍和提问。我是一个预训练的语言模型,专注于回答各种知识性问题。我可以尝试回答你的问题。 关于你提到的问题,utils.general.apply_classifier 是一个函数或方法的名称。从这个名字来看,它可能是一个通用的工具函数,用于应用某种分类器或分类方法。但是,根据你提供的信息,我无法更进一步理解它的具体含义或上下文。如果你能提供更多的信息,例如它是在哪个程序或系统中使用的,或者它的参数和返回值是什么,那么我可能会更有帮助。 如果你有其他的问题,欢迎继续提问,我会尽力回答。 ### 回答2: utils.general.apply_classifier是一个通用的函数,用于将分类器应用于给定的数据集。它接受一个分类器模型和一个数据集作为输入,并输出预测结果。 该函数的第一个参数是分类器模型,可以是任何已经训练好的分类器,如支持向量机(SVM)、随机森林(Random Forest)或逻辑回归(Logistic Regression)。该模型的目的是根据提供的特征对输入样本进行分类。 第二个参数是数据集,这个数据集是一个包含标记的样本的集合。每个样本都由一组特征表示,可以是数值型、离散型或文本型。这些特征将用于分类器模型进行预测。 当函数被调用,它将分类器应用于数据集中的每个样本,并输出对每个样本的预测结果。预测结果可以是类别标签(如"正面"或"负面")或概率值(用于度量样本属于某一类别的置信度)。 该函数在数据集上迭代并调用分类器的predict方法来进行预测。然后,将预测结果存储在一个列表中,并最后返回该列表作为输出。 总之,utils.general.apply_classifier是一个应用分类器模型的通用函数,它可以将分类器应用于给定的数据集,并输出预测结果。 ### 回答3: utils.general.apply_classifier是一个函数,用于应用分类器模型对输入数据进行分类预测。 该函数的作用是通过传入的分类器模型,对输入的数据进行分类预测。函数的输入参数包括分类器模型和待分类的数据。 具体的操作流程如下: 1. 首先,函数会检查传入的分类器模型是否有效。如果模型无效或者不支持分类操作,函数会返回一个错误提示。 2. 接下来,函数会对输入的数据进行预处理,以符合分类器模型的要求。这可能包括特征选择、特征转换、数据标准化等操作,以确保数据能够被模型正确识别和分类。 3. 然后,函数会调用分类器模型的预测方法,传入已处理的数据,并得到预测结果。预测结果可以是分类标签或者类别概率值,具体取决于分类器模型的实现。 4. 最后,函数会返回预测结果,供用户使用或进一步处理。 使用utils.general.apply_classifier函数的好处是,它提供了一个通用的接口来应用分类器模型进行分类预测。用户无需关心底层的分类器模型实现细节,只需要提供模型和数据即可。这样可以大大简化分类预测的操作流程,提高代码的复用性和可维护性。 需要注意的是,函数的输出结果仅代表模型对输入数据的预测结果,并不一定准确。分类器模型的准确率和性能取决于模型的训练质量和数据的特征。用户在使用该函数应该对分类结果进行验证和评估,以确保结果的可靠性和可信度。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值