Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

CIFAR 10 Dataset: Load and Use in Python

  • Vignya DurvasulaVignya Durvasula
  • November 24, 2026
  • Python Programming Examples
CIFAR 10 Dataset: Load and Use in Python

For an image-classification task, CIFAR-10 provides labeled examples for training and evaluation. It contains 60,000 small RGB images divided among ten classes.

This article explains how Python exposes CIFAR-10 data and how to inspect image and label shapes before preprocessing.

TL;DR

CIFAR-10 is a labeled image dataset with 60,000 small RGB images, and Python libraries expose its standard training and test splits through different interfaces.

  • It has 10 object classes and each image is 32 by 32 pixels.
  • Keras returns NumPy arrays, while torchvision and TensorFlow Datasets provide dataset-style access.
  • Check image and label shapes before preprocessing or fitting a model.

What Is the CIFAR-10 Dataset?

CIFAR-10 is a labeled image set created by Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton. Its name refers to the Canadian Institute for Advanced Research. I use the official dataset page for split counts because it defines the original batches.

The official dataset has 60,000 32-by-32 RGB images, split into 50,000 training and 10,000 test examples. Each image carries one category label.

The categories are airplane, automobile, bird, cat, deer, dog, frog, horse, ship, and truck. The original files contain five training batches and one test batch. The test batch has 1,000 examples per class, and the training batches have 5,000 per class altogether.

Ten class names in the CIFAR-10 dataset
The ten CIFAR-10 categories, from airplane to truck.

CIFAR-100 uses finer labels grouped into superclasses. Choose it when that label hierarchy fits the task. These tiny images may not suit every computer-vision task.

Why CIFAR-10 matters in machine learning

CIFAR-10 gives researchers and learners a shared image-classification task. A model receives a small color image and predicts one of ten labels, so experiments can focus on the classifier rather than collecting and labeling a new image set.

The fixed training and test division gives experiments a shared evaluation setup. Training examples fit model parameters, while the test examples check performance on data held back from fitting. Interpret a score alongside the split and evaluation method used to produce it.

The small image dimensions make input handling suitable for teaching and baseline experiments. Details lost at 32 by 32 pixels cannot be recovered by choosing a more elaborate model. A CIFAR-10 result describes this benchmark, not automatically photographs from a different camera or label scheme.

The original dataset documentation describes the class labels as mutually exclusive, so standard CIFAR-10 classification assigns one category to each image. Category boundaries matter when reading mistakes. For instance, pickup trucks are excluded from both automobile and truck in CIFAR-10, while CIFAR-100 includes pickup truck as its own class.

For a first experiment, fit with the official training split and reserve the test split for evaluation. Repeatedly tuning choices against test results makes them part of development rather than a clean final check. Keep a validation split separate when model selection needs repeated checks.

When comparing two approaches, hold the dataset split and preprocessing choices constant. Otherwise a changed score can reflect a different input pipeline rather than the model change under study. Record whether pixels were scaled and whether augmentation was used so another reader can interpret the result.

Class balance is another useful check. The official files contain 6,000 images per class overall, with the test batch supplying 1,000 from each category. This supports class-by-class evaluation instead of relying on a single aggregate score, which can conceal a model that struggles with one label.

Exploring CIFAR-100, an extended version of CIFAR-10

CIFAR-100 keeps the 60,000-image total and 32-by-32 color format, but divides its labels among 100 fine classes rather than ten. Each fine class has 500 training examples and 100 test examples. Those classes are grouped into 20 superclasses, with five fine classes in each group.

Each CIFAR-100 image has both a fine label and a coarse superclass label. The fine label identifies the specific class, while the coarse label identifies its broader group. For example, a dataset consumer can evaluate predictions at either level when the chosen loader exposes both labels.

This finer label set changes the classification task from broad categories to narrower ones. CIFAR-100 distinguishes more kinds of vehicles or animals, with fewer examples for each fine class. A score on it is not a direct substitute for a CIFAR-10 score.

Check the loader’s documented target fields before adapting code between the datasets. A CIFAR-10 pipeline expecting one class index may need to choose between CIFAR-100’s fine and coarse targets. The TensorFlow Datasets catalog documents both labels as separate features, and the original Toronto dataset page provides the class hierarchy.

How to Load CIFAR-10 in Python Step by Step

I compare the three documented interfaces here because they return data in different forms. Keras returns arrays, torchvision exposes indexed samples, and TensorFlow Datasets supplies named splits.

Step 1: Choose a loader and load the split

Keras provides a direct loader for scripts and notebooks. Its load_data function returns training images and labels, followed by test images and labels.

Documented image shapes are (50000, 32, 32, 3) and (10000, 32, 32, 3), with label shapes (50000, 1) and (10000, 1). Pixel values range from 0 through 255.

I ran the loader script, but its first import failed because TensorFlow is absent. Python raised ModuleNotFoundError because the tensorflow module is missing. Install TensorFlow in the intended environment, then inspect the four returned array shapes.

ModuleNotFoundError: No module named 'tensorflow'
Terminal reports TensorFlow is missing when running the CIFAR-10 loader
The Keras loader command stops at its TensorFlow import when that package is unavailable.

Step 2: Use the dataset interface for your framework

I favor torchvision when the rest of a project uses PyTorch because its CIFAR10 dataset works with that ecosystem. Its constructor accepts a root directory, a train flag, optional transforms, and a download flag. Indexing the object returns an image and target.

TensorFlow Datasets exposes train and test splits as examples containing an image, label, and identifier. Supervised mode yields image-label pairs instead of a feature dictionary. I would choose it when the next steps use TensorFlow mapping and batching.

These interfaces differ in how code accesses examples. Keras loads arrays for the requested splits, making shape inspection direct while placing arrays in memory.

A torchvision dataset supports indexed access for a training loop or data loader. TFDS represents input as a pipeline that can be mapped and batched.

Do not copy a preprocessing line between these APIs without checking its input. Keras image arrays are commonly represented with channels last, while a PyTorch transform pipeline commonly operates on tensors with channels first after conversion. The returned shape is the quickest check before plotting or feeding a batch into a model.

Step 3: Inspect labels before preprocessing

Keras labels have a trailing dimension of one. Their integer values map to class names in the documented order, from zero for airplane to nine for truck. Check another loader’s label shape before reusing this indexing.

For models that expect normalized floats, divide pixel values by 255 during preprocessing. Keep the provided test set separate so evaluation uses its intended holdout examples.

CIFAR-10 Loader Checks and Limits

I group these checks by symptom because each points to a different fix. Confirm the framework, files, label shape, and image layout before changing data.

SymptomWhat to checkNext step
No module named tensorflowThe selected interpreter lacks TensorFlow.Install the framework in the intended environment using its official installation guidance.
File not found during loadingThe archive may not have downloaded or extracted into the expected directory.Retry the supported loader and inspect its documented cache location and extraction result.
Label lookup failsLabels may be scalars or one-element arrays, depending on the loader.Print or inspect the label shape, then index according to that API.
Image display has the wrong shapeChannels-first and channels-last layouts differ.Check the framework’s returned shape before plotting or transposing pixels.

The University of Toronto hosts the original dataset. A PyTorch issue opened in July 2026 reports a slow transfer. If a download stalls, check the host and framework guidance instead of disabling certificate checks or swapping URLs.

AskPython’s convolutional neural network tutorial is a next step after data checks. The custom dataset guide covers a separate PyTorch task.

Conclusion

Choose a loader by its return structure and the framework used downstream. Inspect the data before preprocessing, and reserve the supplied test split for evaluation.

Useful sites for CIFAR-10

Use the University of Toronto CIFAR page for the dataset’s original description, class details, batch organization, downloads, and citation guidance. It is the right reference when a question concerns what the released dataset contains rather than how a particular library wraps it.

For Keras array shapes and class ordering, use the Keras CIFAR-10 API.

For PyTorch constructor arguments and transforms, use the torchvision CIFAR10 reference. The TensorFlow Datasets catalog documents named splits and feature keys.

For a catalog-style overview of the task and dataset citation, see the UCI Machine Learning Repository entry. The Toronto technical report, linked from its dataset page, covers collection and labeling methodology. Use first-party library references when checking arguments or returned values.

In short, separate three decisions before training: which split supplies fitting data, which library interface suits the project, and which label representation the code receives. Dataset documentation explains what examples mean, while library references explain how those examples reach a program. This distinction prevents a missing framework from being mistaken for a damaged dataset, or a shape mismatch from being mistaken for an incorrect class label.

For comparisons, report the split and preprocessing. Inspect one sample and its target before mapping a new loader pipeline. When a task needs finer distinctions, compare CIFAR-100’s fine and coarse labels with its intended label scheme so the label choice is clear.

FAQ

Readers often ask these questions about CIFAR-10.

How many classes are in CIFAR-10?

CIFAR-10 has ten classes: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, and truck.

Can I load CIFAR-10 in Google Colab?

Yes. Use the Keras loader in a TensorFlow-enabled notebook, or load the named splits with TensorFlow Datasets. Check the notebook runtime has the framework installed.

How is CIFAR-100 different from CIFAR-10?

Both contain 60,000 32 by 32 color images, but CIFAR-100 has 100 finer classes grouped into 20 superclasses, rather than ten classes.

Vignya Durvasula
Vignya Durvasula
Articles: 125
Python Empty List: How to Check It
Previous Post Python Empty List: How to Check It
Next Post cv2.imwrite: Save Images in Python
cv2.imwrite: Save Images in Python

Related Posts

How to Calculate Distance Between Two Points in Python

How to Calculate Distance Between Two Points in Python

  • November 26, 2026
Maximum A Posteriori Estimation in Python

Maximum A Posteriori Estimation in Python

  • November 24, 2026
Atom IDE: Check Its Status for Python

Atom IDE: Check Its Status for Python

  • November 23, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.