Vision Transformer (ViT) - CIFAR-10 Image Classification

A custom Vision Transformer (ViT) implemented in PyTorch and trained on the CIFAR-10 dataset for image classification.

This project explores Transformer-based architectures for computer vision, implementing the Vision Transformer approach and training it using mixed-precision training for improved computational efficiency.

The model was trained for 20 epochs on CIFAR-10 using PyTorch.

Model Details

Model Description

This model is a custom implementation of a Vision Transformer (ViT) designed for image classification.

Unlike traditional Convolutional Neural Networks (CNNs), which process images using convolutional operations, Vision Transformers divide an image into smaller patches, project them into embeddings, and process these embeddings using Transformer encoder blocks.

The model uses self-attention mechanisms to learn relationships between different image patches and generate representations useful for image classification.

The model was trained on CIFAR-10, a widely used benchmark dataset containing 60,000 color images across 10 different object categories.

Key Highlights:

  • Custom Vision Transformer architecture implemented in PyTorch.
  • Trained on the CIFAR-10 dataset.
  • Patch-based image representation.
  • Transformer encoder blocks with self-attention.
  • Mixed-precision training using automatic mixed precision (AMP).
  • 20 training epochs.
  • GPU-accelerated training.

Model Information

  • Developed by: Aditya Chaubey
  • Model type: Vision Transformer (ViT)
  • Task: Image Classification
  • Framework: PyTorch
  • Dataset: CIFAR-10
  • Training epochs: 20
  • Batch size: 64
  • Training precision: Mixed Precision (AMP)
  • License: MIT
  • Language(s): Not applicable

Model Sources


Uses

Direct Use

The model can be used directly for classifying images into one of the ten CIFAR-10 categories.

The supported classes are:

  1. Airplane
  2. Automobile
  3. Bird
  4. Cat
  5. Deer
  6. Dog
  7. Frog
  8. Horse
  9. Ship
  10. Truck

Users can load the trained model weights and perform inference on compatible input images.

Downstream Use

The model can serve as a starting point for:

  • Experimenting with Vision Transformer architectures.
  • Learning Transformer-based computer vision.
  • Comparing CNNs and Vision Transformers.
  • Fine-tuning on similar image classification datasets.
  • Exploring attention mechanisms in computer vision.
  • Educational and research experiments.

Out-of-Scope Use

This model is not intended for:

  • General-purpose image classification.
  • Medical image diagnosis.
  • Real-world object detection.
  • Image segmentation.
  • Safety-critical applications.
  • Classification of images outside the CIFAR-10 categories without additional training or evaluation.

Bias, Risks, and Limitations

Although CIFAR-10 is a commonly used benchmark dataset, the model has several limitations.

  • Dataset limitations: The model was trained specifically on CIFAR-10 and may not generalize well to unrelated datasets.
  • Image resolution: CIFAR-10 contains low-resolution 32 × 32 images. Performance on high-resolution images is not established.
  • Domain generalization: The model may perform poorly on images with different visual characteristics from the training dataset.
  • Training limitations: The model was trained for 20 epochs, and additional training or hyperparameter optimization may improve performance.
  • Evaluation limitations: Performance should be assessed using independent test data and appropriate classification metrics.

Recommendations

Users should:

  • Apply the same preprocessing used during training.
  • Evaluate the model on independent test data.
  • Avoid assuming that performance on CIFAR-10 translates to real-world applications.
  • Consider fine-tuning before applying the model to another dataset.
  • Review the model's evaluation metrics before using it in downstream applications.

How to Get Started with the Model

Requirements

Install the required dependencies:

pip install torch torchvision numpy matplotlib tqdm

Loading the Model

The model architecture must be defined before loading the trained weights.

import torch

# Import your custom Vision Transformer architecture
from model import VisionTransformer

device = torch.device(
    "cuda" if torch.cuda.is_available() else "cpu"
)

# Initialize the model with the same configuration
model = VisionTransformer(
    # Add your architecture parameters here
)

# Load trained weights
checkpoint = torch.load(
    "model.pth",
    map_location=device,
    weights_only=True
)

model.load_state_dict(checkpoint)

model.to(device)
model.eval()

print("Model loaded successfully!")

Image Classification

import torch
from PIL import Image
from torchvision import transforms

classes = [
    "airplane", "automobile", "bird", "cat", "deer",
    "dog", "frog", "horse", "ship", "truck"
]

transform = transforms.Compose([
    transforms.Resize((32, 32)),
    transforms.ToTensor(),
    transforms.Normalize(
        (0.4914, 0.4822, 0.4465),
        (0.2470, 0.2435, 0.2616)
    )
])

image = Image.open("image.jpg").convert("RGB")
image = transform(image).unsqueeze(0).to(device)

with torch.no_grad():
    outputs = model(image)
    prediction = outputs.argmax(dim=1).item()

print("Predicted class:", classes[prediction])

Note: The example assumes a standard CIFAR-10 normalization scheme and a model that accepts 32 × 32 images and returns ten class logits. Adjust the architecture initialization, checkpoint loading, and preprocessing to match your actual implementation.


Training Details

Training Data

The model was trained using the CIFAR-10 dataset.

CIFAR-10 consists of:

  • 60,000 RGB images.
  • 50,000 training images.
  • 10,000 test images.
  • 10 object categories.
  • Image resolution: 32 × 32 pixels.
  • Three color channels (RGB).

Dataset Source: https://www.cs.toronto.edu/~kriz/cifar.html

Training Procedure

The Vision Transformer was implemented and trained using PyTorch.

Training was performed for 20 epochs with a batch size of 64.

Mixed-precision training was enabled to improve computational efficiency and reduce memory consumption during training.

Preprocessing

The CIFAR-10 dataset was loaded using Torchvision.

Preprocessing included:

  • Image conversion to tensors.
  • Image normalization.
  • Resizing or other transformations, if applicable, according to the model configuration.

Training Configuration

Parameter Value
Framework PyTorch
Dataset CIFAR-10
Epochs 20
Batch Size 64
Precision Mixed Precision (AMP)
Task Image Classification
Optimizer Adam]
Loss Function Cross Entropy Loss
Learning Rate 1e-4
Scheduler [None]
Hardware [Tesla T4]

Model Architecture

The model follows the Vision Transformer architecture.

Its main components include:

  • Patch Embedding
  • Positional Embedding
  • Transformer Encoder Blocks
  • Multi-Head Self-Attention
  • Feed-Forward Networks (MLP)
  • Classification Head

Model Architecture Summary (Torchinfo):

Complete torchinfo.summary() output here.

[=====================================================================================
Layer (type:depth-idx)                                       Param #
=====================================================================================
vit                                                          --
├─Patch_Embedding: 1-1                                       16,896
│    └─Conv2d: 2-1                                           12,544
├─Sequential: 1-2                                            --
│    └─TransformerEncoderLayer: 2-2                          --
│    │    └─LayerNorm: 3-1                                   512
│    │    └─MultiheadAttention: 3-2                          263,168
│    │    └─LayerNorm: 3-3                                   512
│    │    └─MLP: 3-4                                         262,912
│    └─TransformerEncoderLayer: 2-3                          --
│    │    └─LayerNorm: 3-5                                   512
│    │    └─MultiheadAttention: 3-6                          263,168
│    │    └─LayerNorm: 3-7                                   512
│    │    └─MLP: 3-8                                         262,912
│    └─TransformerEncoderLayer: 2-4                          --
│    │    └─LayerNorm: 3-9                                   512
│    │    └─MultiheadAttention: 3-10                         263,168
│    │    └─LayerNorm: 3-11                                  512
│    │    └─MLP: 3-12                                        262,912
│    └─TransformerEncoderLayer: 2-5                          --
│    │    └─LayerNorm: 3-13                                  512
│    │    └─MultiheadAttention: 3-14                         263,168
│    │    └─LayerNorm: 3-15                                  512
│    │    └─MLP: 3-16                                        262,912
│    └─TransformerEncoderLayer: 2-6                          --
│    │    └─LayerNorm: 3-17                                  512
│    │    └─MultiheadAttention: 3-18                         263,168
│    │    └─LayerNorm: 3-19                                  512
│    │    └─MLP: 3-20                                        262,912
│    └─TransformerEncoderLayer: 2-7                          --
│    │    └─LayerNorm: 3-21                                  512
│    │    └─MultiheadAttention: 3-22                         263,168
│    │    └─LayerNorm: 3-23                                  512
│    │    └─MLP: 3-24                                        262,912
├─LayerNorm: 1-3                                             512
├─Linear: 1-4                                                2,570
=====================================================================================
Total params: 3,195,146
Trainable params: 3,195,146
Non-trainable params: 0
=====================================================================================]

Evaluation

Metric Result
Test Accuracy 69%
Test Loss 0.98
Training Epochs 20

Evaluation metrics should be updated with the actual results from your training and testing process.


Hardware and Software

Software

  • Python
  • PyTorch
  • Torchvision
  • NumPy
  • Matplotlib
  • tqdm

Hardware

  • GPU: [Tesla T4 cuda]

License

This model is released under the MIT License.

You are free to use, modify, and distribute this project in accordance with the terms of the license.


Acknowledgements

  • Hugging Face for providing the model hosting platform.
  • PyTorch for the deep learning framework.
  • The CIFAR-10 dataset creators for providing the benchmark dataset.

Built with PyTorch | Computer Vision | Vision Transformers

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for adityachaubey/vision_transform

Unable to build the model tree, the base model loops to the model itself. Learn more.

Dataset used to train adityachaubey/vision_transform

Space using adityachaubey/vision_transform 1