class_names = image_datasets['train'].classes
时间: 2024-04-18 17:23:38 浏览: 128
这行代码是用来获取训练集数据的类别名称列表。`image_datasets['train']`返回了训练集的`ImageFolder`对象,而`.classes`则是一个属性,它包含了训练集中所有类别的名称。
通过将训练集的`ImageFolder`对象中的`.classes`属性赋值给`class_names`变量,你可以得到一个存储了训练集类别名称的列表,以便在之后的代码中使用。这样可以方便地查看和操作训练集的类别信息。
相关问题
yolov7train.py详解
yolov7train.py 是使用 YOLOv7 算法进行目标检测的训练脚本。下面对 yolov7train.py 的主要代码进行简单的解释:
1. 导入相关库
```python
import argparse
import yaml
import time
import torch
from torch.utils.data import DataLoader
from torchvision import datasets
from models.yolov7 import Model
from utils.datasets import ImageFolder
from utils.general import (
check_img_size, non_max_suppression, apply_classifier, scale_coords,
xyxy2xywh, plot_one_box, strip_optimizer, set_logging)
from utils.torch_utils import (
select_device, time_synchronized, load_classifier, model_info)
```
这里导入了 argparse 用于解析命令行参数,yaml 用于解析配置文件,time 用于记录时间,torch 用于神经网络训练,DataLoader 用于读取数据集,datasets 和 ImageFolder 用于加载数据集,Model 用于定义 YOLOv7 模型,各种工具函数用于辅助训练。
2. 定义命令行参数
```python
parser = argparse.ArgumentParser()
parser.add_argument('--data', type=str, default='data.yaml', help='dataset.yaml path')
parser.add_argument('--hyp', type=str, default='hyp.yaml', help='hyperparameters path')
parser.add_argument('--epochs', type=int, default=300)
parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes')
parser.add_argument('--rect', action='store_true', help='rectangular training')
parser.add_argument('--resume', nargs='?', const='yolov7.pt', default=False, help='resume most recent training')
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
parser.add_argument('--notest', action='store_true', help='only test final epoch')
parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
opt = parser.parse_args()
```
这里定义了许多命令行参数,包括数据集路径、超参数路径、训练轮数、批量大小、图片大小、是否使用矩形训练、是否从最近的检查点恢复训练、是否只保存最终的检查点、是否只测试最终的模型、是否进行超参数进化、gsutil 存储桶等。
3. 加载数据集
```python
with open(opt.data) as f:
data_dict = yaml.load(f, Loader=yaml.FullLoader)
train_path = data_dict['train']
test_path = data_dict['test']
num_classes = data_dict['nc']
names = data_dict['names']
train_dataset = ImageFolder(train_path, img_size=opt.img_size[0], rect=opt.rect)
test_dataset = ImageFolder(test_path, img_size=opt.img_size[1], rect=True)
batch_size = opt.batch_size
train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=8, pin_memory=True, collate_fn=train_dataset.collate_fn)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size * 2, num_workers=8, pin_memory=True, collate_fn=test_dataset.collate_fn)
```
这里读取了数据集的配置文件,包括训练集、测试集、类别数和类别名称等信息。然后使用 ImageFolder 加载数据集,设置图片大小和是否使用矩形训练。最后使用 DataLoader 加载数据集,并设置批量大小、是否 shuffle、是否使用 pin_memory 等参数。
4. 定义 YOLOv7 模型
```python
model = Model(opt.hyp, num_classes, opt.img_size)
model.nc = num_classes
device = select_device(opt.device, batch_size=batch_size)
model.to(device).train()
criterion = model.loss
optimizer = torch.optim.SGD(model.parameters(), lr=hyp['lr0'], momentum=hyp['momentum'], weight_decay=hyp['weight_decay'])
scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=1, T_mult=2)
start_epoch = 0
best_fitness = 0.0
```
这里使用 Model 类定义了 YOLOv7 模型,并将其放到指定设备上进行训练。使用交叉熵损失函数作为模型的损失函数,使用 SGD 优化器进行训练,并使用余弦退火学习率调整策略。定义了起始轮数、最佳精度等变量。
5. 开始训练
```python
for epoch in range(start_epoch, opt.epochs):
model.train()
mloss = torch.zeros(4).to(device) # mean losses
for i, (imgs, targets, paths, _) in enumerate(train_dataloader):
ni = i + len(train_dataloader) * epoch # number integrated batches (since train start)
imgs = imgs.to(device)
targets = targets.to(device)
loss, _, _ = model(imgs, targets)
loss.backward()
optimizer.step()
optimizer.zero_grad()
mloss = (mloss * i + loss.detach().cpu()) / (i + 1) # update mean losses
# Print batch results
if ni % 20 == 0:
print(f'Epoch {epoch}/{opt.epochs - 1}, Batch {i}/{len(train_dataloader) - 1}, lr={optimizer.param_groups[0]["lr"]:.6f}, loss={mloss[0]:.4f}')
# Update scheduler
scheduler.step()
# Update Best fitness
with torch.no_grad():
fitness = model_fitness(model)
if fitness > best_fitness:
best_fitness = fitness
# Save checkpoint
if (not opt.nosave) or (epoch == opt.epochs - 1):
ckpt = {
'epoch': epoch,
'best_fitness': best_fitness,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict()
}
torch.save(ckpt, f'checkpoints/yolov7_epoch{epoch}.pt')
# Test
if not opt.notest:
t = time_synchronized()
model.eval()
for j, (imgs, targets, paths, shapes) in enumerate(test_dataloader):
if j == 0:
pred = model(imgs.to(device))
pred = non_max_suppression(pred, conf_thres=0.001, iou_thres=0.6)
else:
break
t1 = time_synchronized()
if isinstance(pred, int) or isinstance(pred, tuple):
print(f'Epoch {epoch}/{opt.epochs - 1}, test_loss={mloss[0]:.4f}, test_mAP={0.0}')
else:
pred = pred[0].cpu()
iou_thres = 0.5
niou = [iou_thres] * num_classes
ap, p, r = ap_per_class(pred, targets, shapes, iou_thres=niou)
mp, mr, map50, f1, _, _ = stats(ap, p, r, gt=targets)
print(f'Epoch {epoch}/{opt.epochs - 1}, test_loss={mloss[0]:.4f}, test_mAP={map50:.2f} ({mr*100:.1f}/{mp*100:.1f})')
# Plot images
if epoch == 0 and j == 0:
for i, det in enumerate(pred): # detections per image
img = cv2.imread(paths[i]) # BGR
img = plot_results(img, det, class_names=names)
cv2.imwrite(f'runs/test{i}.jpg', img)
if i == 3:
break
```
这里进行了多个 epoch 的训练。在每个 epoch 中,对于每个批量的数据,先将数据移动到指定设备上,然后计算模型的损失函数,并进行反向传播和梯度下降。在每个 epoch 结束时,更新学习率调整策略和最佳精度,保存当前的检查点。如果 opt.notest 为 False,则进行测试,并输出测试结果。最后,如果是第一个 epoch,则绘制部分图像用于可视化。
torchvision.datasets.CIFAR10源码
以下是torchvision.datasets.CIFAR10的源码:
```
import torch.utils.data as data
from PIL import Image
import os
import os.path
import numpy as np
import pickle
class CIFAR10(data.Dataset):
"""`CIFAR10 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.
Args:
root (string): Root directory of dataset where directory
``cifar-10-batches-py`` exists or will be downloaded to if download is set to True.
train (bool, optional): If True, creates dataset from training set, otherwise
creates from test set.
transform (callable, optional): A function/transform that takes in an PIL image
and returns a transformed version. E.g, ``transforms.RandomCrop``
target_transform (callable, optional): A function/transform that takes in the
target and transforms it.
Returns:
tuple: (image, target) where target is index of the target class.
"""
base_folder = 'cifar-10-batches-py'
url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
filename = "cifar-10-python.tar.gz"
tgz_md5 = 'c58f30108f718f92721af3b95e74349a'
train_list = [
['data_batch_1', 'c99cafc152244af753f735de768cd75f'],
['data_batch_2', 'd4bba439e000b95fd0a9bffe97cbabec'],
['data_batch_3', '54ebc095f3ab1f03828d0aae7e51cd9d'],
['data_batch_4', '634d18415352ddfa80567beed471001a'],
['data_batch_5', '482c414d41f54cd18b22e5b47cb7c3cb'],
]
test_list = [
['test_batch', '40351d587109b95175f43aff81a1287e'],
]
def __init__(self, root, train=True,
transform=None, target_transform=None,
download=False):
self.root = os.path.expanduser(root)
self.transform = transform
self.target_transform = target_transform
self.train = train # training set or test set
if download:
self.download()
if not self._check_integrity():
raise RuntimeError('Dataset not found or corrupted.' +
' You can use download=True to download it')
if self.train:
downloaded_list = self.train_list
else:
downloaded_list = self.test_list
self.data = []
self.targets = []
# now load the picked numpy arrays
for file_name, checksum in downloaded_list:
file_path = os.path.join(self.root, self.base_folder, file_name)
with open(file_path, 'rb') as f:
if 'meta' in file_name:
data_dict = pickle.load(f, encoding='latin1')
self.classes = data_dict['label_names']
else:
data_dict = pickle.load(f, encoding='latin1')
self.data.append(data_dict['data'])
self.targets.extend(data_dict['labels'])
self.data = np.vstack(self.data).reshape(-1, 3, 32, 32)
self.data = self.data.transpose((0, 2, 3, 1)) # convert to HWC
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.targets[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.data)
def _check_integrity(self):
root = self.root
for fentry in (self.train_list + self.test_list):
filename, md5 = fentry[0], fentry[1]
fpath = os.path.join(root, self.base_folder, filename)
if not check_integrity(fpath, md5):
return False
return True
def download(self):
import tarfile
if self._check_integrity():
print('Files already downloaded and verified')
return
download_url(self.url, self.root, self.filename, self.tgz_md5)
# extract file
with tarfile.open(os.path.join(self.root, self.filename), "r:gz") as tar:
tar.extractall(path=self.root)
print('Done!')
class CIFAR100(CIFAR10):
"""`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.
This is a subclass of the `CIFAR10` Dataset.
"""
base_folder = 'cifar-100-python'
url = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz"
filename = "cifar-100-python.tar.gz"
tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'
train_list = [
['train', '16019d7e3df5f24257cddd939b257f8d'],
]
test_list = [
['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'],
]
def __init__(self, root, train=True,
transform=None, target_transform=None,
download=False):
super(CIFAR100, self).__init__(root, train=train,
transform=transform,
target_transform=target_transform,
download=download)
```
该代码定义了CIFAR10和CIFAR100数据集的类,这些数据集是用于图像分类任务的标准数据集之一。每个数据集都有一个训练集和一个测试集,每个图像都有一个标签,表示它所属的类别。
这些类继承自torch.utils.data.Dataset类,并实现了__getitem__和__len__方法。它们还提供了下载和检查数据集完整性的方法。
在初始化阶段,数据集从pickle文件中加载数据和标签,并将其存储在self.data和self.targets中。__getitem__方法返回图像和标签的元组,__len__方法返回数据集中图像的数量。
阅读全文