ttvnet / Image /utils /dataset_utils.py
RRFRRF
add some cv models and update readme.md
bdbd148
raw
history blame
1.95 kB
import torch
import torchvision
import torchvision.transforms as transforms
import os
def get_cifar10_dataloaders(batch_size=128, num_workers=2, local_dataset_path=None):
"""获取CIFAR10数据集的数据加载器
Args:
batch_size: 批次大小
num_workers: 数据加载的工作进程数
local_dataset_path: 本地数据集路径,如果提供则使用本地数据集,否则下载
Returns:
trainloader: 训练数据加载器
testloader: 测试数据加载器
"""
# 数据预处理
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
# 设置数据集路径
if local_dataset_path:
print(f"使用本地数据集: {local_dataset_path}")
download = False
dataset_path = local_dataset_path
else:
print("未指定本地数据集路径,将下载数据集")
download = True
dataset_path = '../dataset'
# 创建数据集路径
if not os.path.exists(dataset_path):
os.makedirs(dataset_path)
trainset = torchvision.datasets.CIFAR10(
root=dataset_path, train=True, download=download, transform=transform_train)
trainloader = torch.utils.data.DataLoader(
trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers)
testset = torchvision.datasets.CIFAR10(
root=dataset_path, train=False, download=download, transform=transform_test)
testloader = torch.utils.data.DataLoader(
testset, batch_size=100, shuffle=False, num_workers=num_workers)
return trainloader, testloader