torchvision.datasets.cifar10
时间: 2023-04-29 15:03:31 浏览: 99
torchvision.datasets.cifar10 是 PyTorch 中的一个数据集,其中包含了 60,000 张 32x32 的彩色图像,分成 10 个类别,每类 6000 张图像。这些图像来自 CIFAR-10 数据集,是用于图像识别的常用数据集之一。
相关问题
torchvision.datasets.CIFAR10
`torchvision.datasets.CIFAR10` 是一个 PyTorch 中的数据集类,它包含了 10 类不同类型的图片数据,例如飞机、汽车、鸟类、猫、鹿、狗、青蛙、马、船和卡车。每一个图片都是 $32 \times 32$ 的彩色图片,可以用来进行图像分类任务的训练和测试。这个数据集通常用于计算机视觉领域的研究和实验。你可以使用 `torchvision.datasets.CIFAR10` 类来加载 CIFAR-10 数据集,然后将其转换为 PyTorch 的张量形式,以便进行模型训练和测试。
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__方法返回数据集中图像的数量。
阅读全文