ViT
Vision Transformer
A vision model that splits images into patches and feeds them to a Transformer. An alternative to CNNs with excellent performance on large datasets.
Vision Transformer
A vision model that splits images into patches and feeds them to a Transformer. An alternative to CNNs with excellent performance on large datasets.
Vision Transformer (ViT) is an image classification model published by Google Research in 2020, and it was the first to successfully apply the Transformer architecture, which had succeeded in natural language processing, to computer vision. In the paper "An Image is Worth 16x16 Words," it presented an innovative approach of splitting an image into 16x16 pixel patches and processing them like words.
Before ViT, computer vision was dominated by CNNs (Convolutional Neural Networks). CNNs are effective at extracting local features, but they had limitations in capturing global relationships across an entire image. ViT solved this problem by simultaneously learning the relationships among all patches of an image through the Self-Attention mechanism.
ViT works as follows. The input image is split into fixed-size patches (usually 16x16), and each patch is converted into a linear embedding. After positional information is added and the result is fed into the Transformer encoder, relationships between patches are learned through Multi-Head Self-Attention. The output of the CLS token is used to perform the final classification.
In practice, ViT outperforms CNNs on large-scale datasets such as ImageNet. It is especially strong in the pre-training followed by fine-tuning paradigm, and it is widely used as the vision encoder of multimodal models such as CLIP, DALL-E, and Stable Diffusion. It can be easily used through Hugging Face Transformers.
import torch
from transformers import ViTImageProcessor, ViTForImageClassification
from PIL import Image
import requests
# 1. 모델과 프로세서 로드
model_name = "google/vit-base-patch16-224"
processor = ViTImageProcessor.from_pretrained(model_name)
model = ViTForImageClassification.from_pretrained(model_name)
# 2. 이미지 로드 (URL 또는 로컬 파일)
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
# 3. 이미지 전처리 및 추론
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
# 4. 예측 결과 출력
predicted_class_idx = logits.argmax(-1).item()
predicted_label = model.config.id2label[predicted_class_idx]
confidence = torch.softmax(logits, dim=-1)[0, predicted_class_idx].item()
print(f"예측 클래스: {predicted_label}")
print(f"신뢰도: {confidence:.2%}")
# 5. Top-5 예측 출력
top5_probs, top5_indices = torch.topk(torch.softmax(logits, dim=-1), 5)
print("\nTop-5 예측:")
for prob, idx in zip(top5_probs[0], top5_indices[0]):
label = model.config.id2label[idx.item()]
print(f" {label}: {prob.item():.2%}")
# 6. 특징 추출 (임베딩)
from transformers import ViTModel
feature_model = ViTModel.from_pretrained(model_name)
with torch.no_grad():
features = feature_model(**inputs)
cls_embedding = features.last_hidden_state[:, 0, :] # CLS 토큰
print(f"\nCLS 임베딩 차원: {cls_embedding.shape}") # [1, 768]
# 7. 커스텀 데이터셋 파인튜닝 예시
from transformers import Trainer, TrainingArguments
from datasets import load_dataset
# 데이터셋 로드 (예: CIFAR-10)
# dataset = load_dataset("cifar10")
#
# training_args = TrainingArguments(
# output_dir="./vit-finetuned",
# num_train_epochs=3,
# per_device_train_batch_size=16,
# learning_rate=2e-5,
# evaluation_strategy="epoch"
# )
#
# trainer = Trainer(
# model=model,
# args=training_args,
# train_dataset=dataset["train"],
# eval_dataset=dataset["test"]
# )
ViT Model Variant Comparison (ImageNet-1K Top-1 Accuracy)
| Model | Parameter | ImageNet Acc. | Patch Size | Input Resolution |
|---|---|---|---|---|
| ViT-Tiny | 5.7M | 72.2% | 16x16 | 224x224 |
| ViT-Small | 22M | 79.9% | 16x16 | 224x224 |
| ViT-Base | 86M | 84.5% | 16x16 | 384x384 |
| ViT-Large | 307M | 87.8% | 16x16 | 384x384 |
| ViT-Huge | 632M | 88.5% | 14x14 | 518x518 |
CNN vs ViT Comparison
"We're considering ViT as an image classification model, but our dataset is only about 100,000 images, so a CNN-based EfficientNet might be better. ViT seems best used by fine-tuning a large-scale pre-trained model."
"What's different about ViT compared to CNN?" - "CNNs hierarchically extract local features with convolutions, but ViT learns global relationships among all patches at once with Self-Attention. So it has strengths on large-scale data, and on small data it may struggle to generalize because of insufficient inductive bias."
"The image encoders of CLIP and Stable Diffusion are ViT-based. In particular, CLIP ViT-L/14 has excellent image-text alignment, so it's widely used for zero-shot image classification and retrieval."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Training ViT from scratch requires at least several million images. Training from scratch on about 10,000 images leads to severe overfitting. Be sure to fine-tune a pre-trained model.
ViT is trained with a fixed number of patches. vit-base-patch16-224 divides a 224x224 image into 14x14 patches. If you feed images of a different resolution, the position embeddings no longer match and performance degrades. The processor resizes automatically, but if the original resolution differs greatly, information is lost.
Use ViTForImageClassification for classification and ViTModel for feature extraction. For object detection/segmentation, Swin Transformer or DETRs are more suitable. Use CLIP ViT for multimodal tasks.