Skip to content

CIFAR10

The CIFAR-10 dataset consists of 32x32 color images classified into 10 classes.

The dataset is split into:

  • train: 45,000 images for training;
  • dev: 5,000 images for development (validation);
  • test: 2,000 images for testing; note that this is not the official CIFAR-10 test set.

npfl138.datasets.cifar10.CIFAR10

Source code in npfl138/datasets/cifar10.py
 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
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
class CIFAR10:
    C: int = 3
    """The number of image channels."""
    H: int = 32
    """The image height."""
    W: int = 32
    """The image width."""
    LABELS: int = 10
    """The number of labels."""
    LABEL_NAMES: list[str] = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
    """The names of the labels."""

    Element = TypedDict("Element", {"image": torch.Tensor, "label": torch.Tensor})
    """The type of a single dataset element."""
    Elements = TypedDict("Elements", {"images": torch.Tensor, "labels": torch.Tensor})
    """The type of the whole dataset."""

    URL: str = "https://ufal.mff.cuni.cz/~straka/courses/npfl138/2526/datasets"

    class Dataset(torch.utils.data.Dataset):
        def __init__(self, data: "CIFAR10.Elements") -> None:
            self._data = {key: torch.as_tensor(value) for key, value in data.items()}
            self._data["images"] = self._data["images"].movedim(-1, 1)
            self._data["labels"] = self._data["labels"].view(-1)

        @property
        def data(self) -> "CIFAR10.Elements":
            """Return the whole dataset as a `CIFAR10.Elements` object."""
            return self._data

        def __len__(self) -> int:
            """Return the number of elements in the dataset."""
            return len(self._data["images"])

        def __getitem__(self, index: int) -> "CIFAR10.Element":
            """Return the `index`-th element of the dataset."""
            return {key.removesuffix("s"): value[index] for key, value in self._data.items()}

    def __init__(self, sizes: dict[str, int] = {}) -> None:
        """Load the CIFAR10 dataset, downloading it if necessary.

        Parameters:
          sizes: An optional dictionary overriding the sizes of the `train`, `dev`, and `test` splits.
        """
        path = download_url_to_file(self.URL, "cifar10_competition.npz")
        cifar = np.load(path)
        for dataset in ["train", "dev", "test"]:
            data = {key[len(dataset) + 1:]: cifar[key][:sizes.get(dataset, None)]
                    for key in cifar if key.startswith(dataset)}
            setattr(self, dataset, self.Dataset(data))

    train: Dataset
    """The training dataset."""
    dev: Dataset
    """The development dataset."""
    test: Dataset
    """The test dataset; note that this is not the official CIFAR-10 test set."""

    # Evaluation infrastructure.
    @staticmethod
    def evaluate(gold_dataset: Dataset, predictions: Sequence[int]) -> float:
        """Evaluate the `predictions` against the gold dataset.

        Returns:
          accuracy
        """
        gold = gold_dataset.data["labels"]

        if len(predictions) != len(gold):
            raise RuntimeError("The predictions are of different size than gold data: {} vs {}".format(
                len(predictions), len(gold)))

        correct = sum(bool(gold[i] == predictions[i]) for i in range(len(gold)))
        return correct / len(gold)

    @staticmethod
    def evaluate_file(gold_dataset: Dataset, predictions_file: TextIO) -> float:
        """Evaluate the file with predictions against the gold dataset.

        Returns:
          accuracy
        """
        predictions = [int(line) for line in predictions_file]
        return CIFAR10.evaluate(gold_dataset, predictions)

C class-attribute instance-attribute

C: int = 3

The number of image channels.

H class-attribute instance-attribute

H: int = 32

The image height.

W class-attribute instance-attribute

W: int = 32

The image width.

LABELS class-attribute instance-attribute

LABELS: int = 10

The number of labels.

LABEL_NAMES class-attribute instance-attribute

LABEL_NAMES: list[str] = [
    "airplane",
    "automobile",
    "bird",
    "cat",
    "deer",
    "dog",
    "frog",
    "horse",
    "ship",
    "truck",
]

The names of the labels.

Element class-attribute instance-attribute

Element = TypedDict('Element', {'image': Tensor, 'label': Tensor})

The type of a single dataset element.

Elements class-attribute instance-attribute

Elements = TypedDict('Elements', {'images': Tensor, 'labels': Tensor})

The type of the whole dataset.

Dataset

Bases: Dataset

Source code in npfl138/datasets/cifar10.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Dataset(torch.utils.data.Dataset):
    def __init__(self, data: "CIFAR10.Elements") -> None:
        self._data = {key: torch.as_tensor(value) for key, value in data.items()}
        self._data["images"] = self._data["images"].movedim(-1, 1)
        self._data["labels"] = self._data["labels"].view(-1)

    @property
    def data(self) -> "CIFAR10.Elements":
        """Return the whole dataset as a `CIFAR10.Elements` object."""
        return self._data

    def __len__(self) -> int:
        """Return the number of elements in the dataset."""
        return len(self._data["images"])

    def __getitem__(self, index: int) -> "CIFAR10.Element":
        """Return the `index`-th element of the dataset."""
        return {key.removesuffix("s"): value[index] for key, value in self._data.items()}

data property

data: Elements

Return the whole dataset as a CIFAR10.Elements object.

__len__

__len__() -> int

Return the number of elements in the dataset.

Source code in npfl138/datasets/cifar10.py
54
55
56
def __len__(self) -> int:
    """Return the number of elements in the dataset."""
    return len(self._data["images"])

__getitem__

__getitem__(index: int) -> Element

Return the index-th element of the dataset.

Source code in npfl138/datasets/cifar10.py
58
59
60
def __getitem__(self, index: int) -> "CIFAR10.Element":
    """Return the `index`-th element of the dataset."""
    return {key.removesuffix("s"): value[index] for key, value in self._data.items()}

__init__

__init__(sizes: dict[str, int] = {}) -> None

Load the CIFAR10 dataset, downloading it if necessary.

Parameters:

  • sizes (dict[str, int], default: {} ) –

    An optional dictionary overriding the sizes of the train, dev, and test splits.

Source code in npfl138/datasets/cifar10.py
62
63
64
65
66
67
68
69
70
71
72
73
def __init__(self, sizes: dict[str, int] = {}) -> None:
    """Load the CIFAR10 dataset, downloading it if necessary.

    Parameters:
      sizes: An optional dictionary overriding the sizes of the `train`, `dev`, and `test` splits.
    """
    path = download_url_to_file(self.URL, "cifar10_competition.npz")
    cifar = np.load(path)
    for dataset in ["train", "dev", "test"]:
        data = {key[len(dataset) + 1:]: cifar[key][:sizes.get(dataset, None)]
                for key in cifar if key.startswith(dataset)}
        setattr(self, dataset, self.Dataset(data))

train instance-attribute

train: Dataset

The training dataset.

dev instance-attribute

dev: Dataset

The development dataset.

test instance-attribute

test: Dataset

The test dataset; note that this is not the official CIFAR-10 test set.

evaluate staticmethod

evaluate(gold_dataset: Dataset, predictions: Sequence[int]) -> float

Evaluate the predictions against the gold dataset.

Returns:

Source code in npfl138/datasets/cifar10.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@staticmethod
def evaluate(gold_dataset: Dataset, predictions: Sequence[int]) -> float:
    """Evaluate the `predictions` against the gold dataset.

    Returns:
      accuracy
    """
    gold = gold_dataset.data["labels"]

    if len(predictions) != len(gold):
        raise RuntimeError("The predictions are of different size than gold data: {} vs {}".format(
            len(predictions), len(gold)))

    correct = sum(bool(gold[i] == predictions[i]) for i in range(len(gold)))
    return correct / len(gold)

evaluate_file staticmethod

evaluate_file(gold_dataset: Dataset, predictions_file: TextIO) -> float

Evaluate the file with predictions against the gold dataset.

Returns:

Source code in npfl138/datasets/cifar10.py
 99
100
101
102
103
104
105
106
107
@staticmethod
def evaluate_file(gold_dataset: Dataset, predictions_file: TextIO) -> float:
    """Evaluate the file with predictions against the gold dataset.

    Returns:
      accuracy
    """
    predictions = [int(line) for line in predictions_file]
    return CIFAR10.evaluate(gold_dataset, predictions)