第18周:YOLOv5-C3模块实现

目录

前言

一、 前期准备

1. 设置GPU

2. 导入数据

3. 划分数据集

二、搭建包含C3模块的模型

1. 搭建模型

2. 查看模型详情 

三、 训练模型

1. 编写训练函数

2. 编写测试函数

3. 正式训练

四、 结果可视化

1. Loss与Accuracy图

2. 模型评估 

五、总结 

前言

一、 前期准备

1. 设置GPU

import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
import os,PIL,pathlib,warnings

warnings.filterwarnings("ignore")             #忽略警告信息

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device

2. 导入数据

import os,PIL,random,pathlib

data_dir = './8-data/'
data_dir = pathlib.Path(data_dir)

data_paths  = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[1] for path in data_paths]
classeNames

['cloudy', 'rain', 'shine', 'sunrise']

# 关于transforms.Compose的更多介绍可以参考:https://blog.csdn.net/qq_38251616/article/details/124878863
train_transforms = transforms.Compose([
    transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
    # transforms.RandomHorizontalFlip(), # 随机水平翻转
    transforms.ToTensor(),          # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
    transforms.Normalize(           # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
        mean=[0.485, 0.456, 0.406], 
        std=[0.229, 0.224, 0.225])  # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])

test_transform = transforms.Compose([
    transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
    transforms.ToTensor(),          # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
    transforms.Normalize(           # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
        mean=[0.485, 0.456, 0.406], 
        std=[0.229, 0.224, 0.225])  # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])

total_data = datasets.ImageFolder("./8-data/",transform=train_transforms)
total_data

Dataset ImageFolder
    Number of datapoints: 1125
    Root location: ./8-data/
    StandardTransform
Transform: Compose(
               Resize(size=[224, 224], interpolation=bilinear, max_size=None, antialias=None)
               ToTensor()
               Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
           ) 

total_data.class_to_idx

{'cloudy': 0, 'rain': 1, 'shine': 2, 'sunrise': 3} 

3. 划分数据集

train_size = int(0.8 * len(total_data))
test_size  = len(total_data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])
train_dataset, test_dataset

 (<torch.utils.data.dataset.Subset at 0x19600429450>,
 <torch.utils.data.dataset.Subset at 0x196004297e0>)

batch_size = 4

train_dl = torch.utils.data.DataLoader(train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True,
                                           num_workers=1)
test_dl = torch.utils.data.DataLoader(test_dataset,
                                          batch_size=batch_size,
                                          shuffle=True,
                                          num_workers=1)
for X, y in test_dl:
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break

Shape of X [N, C, H, W]:  torch.Size([4, 3, 224, 224])
Shape of y:  torch.Size([4]) torch.int64 

二、搭建包含C3模块的模型

image.png


1. 搭建模型
 

import torch.nn.functional as F

def autopad(k, p=None):  # kernel, padding
    # Pad to 'same'
    if p is None:
        p = k // 2 if isinstance(k, int) else [x // 2 for x in k]  # auto-pad
    return p

class Conv(nn.Module):
    # Standard convolution
    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups
        super().__init__()
        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
        self.bn = nn.BatchNorm2d(c2)
        self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())

    def forward(self, x):
        return self.act(self.bn(self.conv(x)))

class Bottleneck(nn.Module):
    # Standard bottleneck
    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, shortcut, groups, expansion
        super().__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c_, c2, 3, 1, g=g)
        self.add = shortcut and c1 == c2

    def forward(self, x):
        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))

class C3(nn.Module):
    # CSP Bottleneck with 3 convolutions
    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion
        super().__init__()
        c_ = int(c2 * e)  # hidden channels
        self.cv1 = Conv(c1, c_, 1, 1)
        self.cv2 = Conv(c1, c_, 1, 1)
        self.cv3 = Conv(2 * c_, c2, 1)  # act=FReLU(c2)
        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))

    def forward(self, x):
        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))

class model_K(nn.Module):
    def __init__(self):
        super(model_K, self).__init__()
        
        # 卷积模块
        self.Conv = Conv(3, 32, 3, 2) 
        
        # C3模块1
        self.C3_1 = C3(32, 64, 3, 2)
        
        # 全连接网络层,用于分类
        self.classifier = nn.Sequential(
            nn.Linear(in_features=802816, out_features=100),
            nn.ReLU(),
            nn.Linear(in_features=100, out_features=4)
        )
        
    def forward(self, x):
        x = self.Conv(x)
        x = self.C3_1(x)
        x = torch.flatten(x, start_dim=1)
        x = self.classifier(x)

        return x

device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
    
model = model_K().to(device)
model

Using cuda device

model_K(
  (Conv): Conv(
    (conv): Conv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
    (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (act): SiLU()
  )
  (C3_1): C3(
    (cv1): Conv(
      (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (act): SiLU()
    )
    (cv2): Conv(
      (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (act): SiLU()
    )
    (cv3): Conv(
      (conv): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
      (bn): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (act): SiLU()
    )
    (m): Sequential(
      (0): Bottleneck(
        (cv1): Conv(
          (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
        (cv2): Conv(
          (conv): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
      )
      (1): Bottleneck(
        (cv1): Conv(
          (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
        (cv2): Conv(
          (conv): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
      )
      (2): Bottleneck(
        (cv1): Conv(
          (conv): Conv2d(32, 32, kernel_size=(1, 1), stride=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
        (cv2): Conv(
          (conv): Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
          (bn): BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
          (act): SiLU()
        )
      )
    )
  )
  (classifier): Sequential(
    (0): Linear(in_features=802816, out_features=100, bias=True)
    (1): ReLU()
    (2): Linear(in_features=100, out_features=4, bias=True)
  )
)

2. 查看模型详情 

# 统计模型参数量以及其他指标
import torchsummary as summary
summary.summary(model, (3, 224, 224))

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 32, 112, 112]             864
       BatchNorm2d-2         [-1, 32, 112, 112]              64
              SiLU-3         [-1, 32, 112, 112]               0
              Conv-4         [-1, 32, 112, 112]               0
            Conv2d-5         [-1, 32, 112, 112]           1,024
       BatchNorm2d-6         [-1, 32, 112, 112]              64
              SiLU-7         [-1, 32, 112, 112]               0
              Conv-8         [-1, 32, 112, 112]               0
            Conv2d-9         [-1, 32, 112, 112]           1,024
      BatchNorm2d-10         [-1, 32, 112, 112]              64
             SiLU-11         [-1, 32, 112, 112]               0
             Conv-12         [-1, 32, 112, 112]               0
           Conv2d-13         [-1, 32, 112, 112]           9,216
      BatchNorm2d-14         [-1, 32, 112, 112]              64
             SiLU-15         [-1, 32, 112, 112]               0
             Conv-16         [-1, 32, 112, 112]               0
       Bottleneck-17         [-1, 32, 112, 112]               0
           Conv2d-18         [-1, 32, 112, 112]           1,024
      BatchNorm2d-19         [-1, 32, 112, 112]              64
             SiLU-20         [-1, 32, 112, 112]               0
             Conv-21         [-1, 32, 112, 112]               0
           Conv2d-22         [-1, 32, 112, 112]           9,216
      BatchNorm2d-23         [-1, 32, 112, 112]              64
             SiLU-24         [-1, 32, 112, 112]               0
             Conv-25         [-1, 32, 112, 112]               0
       Bottleneck-26         [-1, 32, 112, 112]               0
           Conv2d-27         [-1, 32, 112, 112]           1,024
      BatchNorm2d-28         [-1, 32, 112, 112]              64
             SiLU-29         [-1, 32, 112, 112]               0
             Conv-30         [-1, 32, 112, 112]               0
           Conv2d-31         [-1, 32, 112, 112]           9,216
      BatchNorm2d-32         [-1, 32, 112, 112]              64
             SiLU-33         [-1, 32, 112, 112]               0
             Conv-34         [-1, 32, 112, 112]               0
       Bottleneck-35         [-1, 32, 112, 112]               0
           Conv2d-36         [-1, 32, 112, 112]           1,024
      BatchNorm2d-37         [-1, 32, 112, 112]              64
             SiLU-38         [-1, 32, 112, 112]               0
             Conv-39         [-1, 32, 112, 112]               0
           Conv2d-40         [-1, 64, 112, 112]           4,096
      BatchNorm2d-41         [-1, 64, 112, 112]             128
             SiLU-42         [-1, 64, 112, 112]               0
             Conv-43         [-1, 64, 112, 112]               0
               C3-44         [-1, 64, 112, 112]               0
           Linear-45                  [-1, 100]      80,281,700
             ReLU-46                  [-1, 100]               0
           Linear-47                    [-1, 4]             404
================================================================
Total params: 80,320,536
Trainable params: 80,320,536
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 150.06
Params size (MB): 306.40
Estimated Total Size (MB): 457.04
----------------------------------------------------------------

三、 训练模型
 

1. 编写训练函数

# 训练循环
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小
    num_batches = len(dataloader)   # 批次数目, (size/batch_size,向上取整)

    train_loss, train_acc = 0, 0  # 初始化训练损失和正确率
    
    for X, y in dataloader:  # 获取图片及其标签
        X, y = X.to(device), y.to(device)
        
        # 计算预测误差
        pred = model(X)          # 网络输出
        loss = loss_fn(pred, y)  # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失
        
        # 反向传播
        optimizer.zero_grad()  # grad属性归零
        loss.backward()        # 反向传播
        optimizer.step()       # 每一步自动更新
        
        # 记录acc与loss
        train_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()
            
    train_acc  /= size
    train_loss /= num_batches

    return train_acc, train_loss

2. 编写测试函数

测试函数和训练函数大致相同,但是由于不进行梯度下降对网络权重进行更新,所以不需要传入优化器

def test (dataloader, model, loss_fn):
    size        = len(dataloader.dataset)  # 测试集的大小
    num_batches = len(dataloader)          # 批次数目, (size/batch_size,向上取整)
    test_loss, test_acc = 0, 0
    
    # 当不进行训练时,停止梯度更新,节省计算内存消耗
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)
            
            # 计算loss
            target_pred = model(imgs)
            loss        = loss_fn(target_pred, target)
            
            test_loss += loss.item()
            test_acc  += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc  /= size
    test_loss /= num_batches

    return test_acc, test_loss

3. 正式训练

import copy

optimizer  = torch.optim.Adam(model.parameters(), lr= 1e-4)
loss_fn    = nn.CrossEntropyLoss() # 创建损失函数

epochs     = 20

train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []

best_acc = 0    # 设置一个最佳准确率,作为最佳模型的判别指标

for epoch in range(epochs):
    
    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
    
    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
    
    # 保存最佳模型到 best_model
    if epoch_test_acc > best_acc:
        best_acc   = epoch_test_acc
        best_model = copy.deepcopy(model)
    
    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)
    
    # 获取当前的学习率
    lr = optimizer.state_dict()['param_groups'][0]['lr']
    
    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')
    print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, 
                          epoch_test_acc*100, epoch_test_loss, lr))
    
# 保存最佳模型到文件中
PATH = './best_model.pth'  # 保存的参数文件名
torch.save(model.state_dict(), PATH)

print('Done')
Epoch: 1, Train_acc:72.0%, Train_loss:1.169, Test_acc:88.0%, Test_loss:0.523, Lr:1.00E-04
Epoch: 2, Train_acc:88.4%, Train_loss:0.332, Test_acc:90.2%, Test_loss:0.306, Lr:1.00E-04
Epoch: 3, Train_acc:93.3%, Train_loss:0.217, Test_acc:88.0%, Test_loss:0.444, Lr:1.00E-04
Epoch: 4, Train_acc:95.9%, Train_loss:0.148, Test_acc:91.1%, Test_loss:0.325, Lr:1.00E-04
Epoch: 5, Train_acc:96.2%, Train_loss:0.136, Test_acc:91.1%, Test_loss:0.505, Lr:1.00E-04
Epoch: 6, Train_acc:96.1%, Train_loss:0.107, Test_acc:88.0%, Test_loss:0.534, Lr:1.00E-04
Epoch: 7, Train_acc:95.3%, Train_loss:0.273, Test_acc:89.8%, Test_loss:0.447, Lr:1.00E-04
Epoch: 8, Train_acc:95.7%, Train_loss:0.159, Test_acc:84.0%, Test_loss:0.708, Lr:1.00E-04
Epoch: 9, Train_acc:97.7%, Train_loss:0.104, Test_acc:80.9%, Test_loss:0.869, Lr:1.00E-04
Epoch:10, Train_acc:98.8%, Train_loss:0.052, Test_acc:88.9%, Test_loss:0.366, Lr:1.00E-04
Epoch:11, Train_acc:99.6%, Train_loss:0.013, Test_acc:88.9%, Test_loss:0.349, Lr:1.00E-04
Epoch:12, Train_acc:99.4%, Train_loss:0.019, Test_acc:90.7%, Test_loss:0.409, Lr:1.00E-04
Epoch:13, Train_acc:98.7%, Train_loss:0.030, Test_acc:86.2%, Test_loss:1.125, Lr:1.00E-04
Epoch:14, Train_acc:98.8%, Train_loss:0.048, Test_acc:90.2%, Test_loss:0.507, Lr:1.00E-04
Epoch:15, Train_acc:99.9%, Train_loss:0.008, Test_acc:87.1%, Test_loss:0.634, Lr:1.00E-04
Epoch:16, Train_acc:99.1%, Train_loss:0.022, Test_acc:88.4%, Test_loss:0.650, Lr:1.00E-04
Epoch:17, Train_acc:99.1%, Train_loss:0.032, Test_acc:88.0%, Test_loss:0.641, Lr:1.00E-04
Epoch:18, Train_acc:99.0%, Train_loss:0.039, Test_acc:84.9%, Test_loss:0.761, Lr:1.00E-04
Epoch:19, Train_acc:99.6%, Train_loss:0.027, Test_acc:88.4%, Test_loss:1.076, Lr:1.00E-04
Epoch:20, Train_acc:98.8%, Train_loss:0.065, Test_acc:88.0%, Test_loss:1.131, Lr:1.00E-04
Done

四、 结果可视化

1. Loss与Accuracy图

import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore")               #忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        #分辨率

from datetime import datetime
current_time = datetime.now() # 获取当前时间

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)

plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.xlabel(current_time) # 打卡请带上时间戳,否则代码截图无效

plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

 

2. 模型评估 

best_model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, best_model, loss_fn)
epoch_test_acc, epoch_test_loss
(0.9111111111111111, 0.6467584735704198)
# 查看是否与我们记录的最高准确率一致
epoch_test_acc
0.9111111111111111

五、总结 

初步学习了YOLOv5算法中的C3模块搭建网络,yolo5小且快,优化器的选择也很重要

<think>好的,我现在需要解决用户提到的YOLOv5在解析模型时出现的IndexError问题,具体是在yolo.py的第338行出现“list index out of range”错误。用户还提供了几个相关的引用,我需要先理解这些引用的内容,然后结合YOLOv5的结构来分析可能的原因和解决方案。 首先,用户提供的三个引用都是关于IndexError的问题。引用1是关于YoloX训练时在voc.py的第138行出现的类似错误,解决方案是修改文件路径的处理方式。引用2提到在yolov5的BiLevelRoutingAttention模块添加到common.py后出现错误,这可能与模型结构修改有关。引用3则是在YOLOv3配置文件中类别数设置不正确导致的错误,需要调整filters参数。这些线索提示,IndexError通常与列表索引超出范围有关,可能原因包括文件路径错误、模型结构配置错误或类别数设置不当。 接下来,用户的问题具体是YOLOv5在解析模型时yolo.py第338行的错误。我需要先定位到yolo.py的对应行数,了解那里的代码逻辑。通常,在YOLOv5中,yolo.py负责构建YOLO模型的检测层,涉及到锚点(anchors)、类别数(classes)等参数的配置。第338行可能是在访问某个列表的索引时超出了范围。 可能的原因有几个: 1. **模型配置文件(如.yaml文件)中的参数错误**:例如,anchors设置不正确,或者filters数量不符合要求。每个检测层的filters应为3*(5 + num_classes),如果类别数设置错误,会导致filters计算错误,进而在构建模型时访问错误的索引。 2. **自定义模块或修改后的代码引入错误**:如引用2中提到,添加了BiLevelRoutingAttention模块到common.py,如果该模块实现有误,可能在模型解析时导致层数不匹配,从而引发索引错误。 3. **数据集配置文件中的类别数不匹配**:例如,data.yaml中的nc(类别数)与模型配置文件中的classes参数不一致,导致在计算filters时出现错误。 接下来,我需要验证这些可能性。首先检查用户是否修改了模型配置文件,比如是否在custom.yaml中正确设置了anchors和filters。例如,在YOLOv5中,每个检测层的filters计算公式为3*(5 + num_classes),如果类别数是1,那么filters应该是183*(5+1)=18)。如果用户修改了类别数但没有相应调整filters,就会导致错误。 另外,检查模型结构中的层是否正确连接。例如,在模型配置文件中,如果某层的输入通道数不正确,可能会导致后续层在解析时无法获取到正确的输入维度,从而触发索引越界。 还要考虑用户是否在common.py中添加了自定义模块,如BiLevelRoutingAttention,是否在该模块中正确处理了输入输出通道,是否导致了层数的不匹配。 可能的解决步骤包括: 1. **检查模型配置文件中的anchors和filters参数**:确保每个检测层对应的filters计算正确,符合3*(5 + num_classes)的公式。例如,如果类别数为1,filters应为18。 2. **验证数据集配置文件中的类别数**:确保data.yaml中的nc与模型配置文件中的classes一致。 3. **检查自定义模块的代码**:如果用户添加了新的模块,如BiLevelRoutingAttention,需要确认其实现是否正确,特别是输入输出通道数的处理,以及是否在模型配置文件中正确引用,没有导致层数错误。 4. **查看错误发生的具体代码行**:定位到yolo.py的第338行,查看该行访问了哪个列表的哪个索引,从而确定具体是哪个参数配置错误。例如,可能是anchors的数量与检测层不匹配,或者输出通道数不正确。 例如,假设yolo.py的第338行是在处理检测层的输出时,预期有三个anchors,但实际配置的anchors数量不足,导致访问时索引超出范围。此时需要检查配置文件中的anchors设置,确保每个检测层对应的anchors数量正确。 总结来说,可能的问题根源在于模型配置文件中的参数错误,或者自定义代码引入的结构问题,需要逐一排查这些方面。</think>### YOLOv5模型解析时IndexError问题的解决方案 出现`IndexError: list index out of range`错误通常是由于模型配置或数据路径中的参数设置与代码逻辑不匹配导致的。以下是逐步排查和修复方法: --- #### **1. 检查模型配置文件(.yaml文件)** YOLOv5的模型配置文件(如`yolov5s.yaml`)定义了网络结构和超参数。需重点关注以下部分: - **锚点(anchors)**:确保每个检测层(YOLO层)的锚点数量与代码预期一致。例如: ```yaml anchors: - [10,13, 16,30, 33,23] # P3/8 (小目标检测层) - [30,61, 62,45, 59,119] # P4/16 (中目标检测层) - [116,90, 156,198, 373,326] # P5/32 (大目标检测层) ``` 每个检测层对应3组锚点,若数量不足或格式错误会导致索引越界[^3]。 - **filters参数**: 每个卷积层(尤其是YOLO层前的卷积)的`filters`必须满足公式: $$filters = 3 \times (5 + num\_classes)$$ 例如,类别数`classes=1`时,`filters=18`。若未正确调整,模型解析时会因通道数错误触发索引越界。 --- #### **2. 验证数据集配置文件(data.yaml)** 在`data.yaml`中,确保`nc`(类别数)与模型配置中的`classes`一致: ```yaml # data.yaml示例 train: ./train/images val: ./val/images nc: 1 # 类别数 names: [&#39;cat&#39;] # 类别名称 ``` 若`nc`与模型配置的`classes`不一致,会导致`filters`计算错误[^3]。 --- #### **3. 排查自定义模块的代码** 若添加了自定义模块(如`BiLevelRoutingAttention`),需检查: - **输入/输出通道数**:模块的输入输出是否与相邻层匹配。 - **配置文件中的引用**:是否正确在模型配置文件中调用该模块。例如: ```yaml [[-1, 1, BiLevelRoutingAttention, [256]]] # 可能引发通道数不匹配 ``` 若参数设置错误,会导致后续层解析时索引越界[^2]。 --- #### **4. 检查文件路径格式** 尽管用户未直接提到路径问题,但类似错误可能与路径分隔符有关(如Windows中使用`\`需转义): ```python # 错误示例(路径分隔符未转义) path = "C:\yolov5\data\images" # 反斜杠需转义为`\\` # 正确写法 path = "C:\\yolov5\\data\\images" # 或使用原始字符串r"C:\yolov5\data\images" ``` 路径解析错误可能导致数据加载时触发索引越界[^1]。 --- #### **5. 具体修复步骤** 1. **定位错误代码行**: 打开`yolo.py`第338行,查看具体访问的列表变量。例如: ```python # 假设代码为: anchor = self.anchors[i][j] # 若i或j超出范围会报错 ``` 需检查`self.anchors`的维度是否与模型配置匹配。 2. **调整模型配置**: 根据类别数修改`filters`和`anchors`,例如: ```yaml # yolov5_custom.yaml anchors: - [10,13, 16,30, 33,23] - [30,61, 62,45, 59,119] - [116,90, 156,198, 373,326] # 检测层配置 [[head]] [[-1, 1, Conv, [512, 1, 1]]] [[-1, 3, C3, [512, False]]] [[-1, 1, Conv, [256, 1, 1]]] [[-1, 1, nn.Upsample, [None, 2, &#39;nearest&#39;]]] [[-1, 1, Conv, [18, 1, 1]]] # filters=3*(5+1)=18 ``` 3. **重新训练模型**: 使用修正后的配置运行训练命令: ```bash python train.py --data data.yaml --cfg yolov5_custom.yaml ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值