File size: 1,947 Bytes
bdbd148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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