Ismail Ben Alla

ViT Image Classifier

Vision Transformer From Scratch

Deep learning · Jun 2024 · Completed

An image classifier built from scratch to understand how Vision Transformers work

Built withPyTorchPoetryViTtorchvisionscikit-learnStreamlitMatplotlib

ViT Image Classifier — overview

Overview

Vision Transformers classify images by cutting them into patches and treating those patches like words in a sentence. I wanted to know what each part of that design actually contributes, so I built a Vision Transformer from scratch in PyTorch rather than importing one.

I wrote each component myself: three patch-embedding strategies, learnable position encodings, multi-head self-attention, a custom GELU activation, and a BERT-style [CLS] token whose final state feeds the classifier. I developed it with the Moroccan Data Scientists community's plant-disease team and applied it to tomato and potato leaf disease images.

On a held-out test split covering four tomato leaf classes, the model reached about 81% accuracy (the repo README reports 81.6%). It is an educational-scale model, not benchmarked against large pretrained ViTs.

The question

What does each part of a Vision Transformer actually contribute — can I build patch embedding, the class token, attention, and fine-tuning from scratch and still classify well?

Key features

How it works

  1. Patch the image

    Each image is split into 16x16 patches and projected into embedding vectors, with a learnable [CLS] token added in front.

  2. Add positions

    Learnable position encodings tell the model where each patch came from, since attention alone ignores order.

  3. Encode

    A stack of Transformer blocks applies multi-head self-attention and feed-forward layers so every patch can attend to every other.

  4. Classify

    After a final LayerNorm, the [CLS] token's vector goes through a linear head that outputs class scores.

  5. Train and fine-tune

    Separate train and fine-tune entry points support a transfer-learning workflow, with live loss and accuracy plots during training.

Examples

More test predictions: most leaves are classified correctly, and the errors confuse Bacterial spot with Early blight, two diseases with similar dark lesions.
More test predictions: most leaves are classified correctly, and the errors confuse Bacterial spot with Early blight, two diseases with similar dark lesions.

Tech stack

What I learned

Limitations