| |
| """ |
| create_notebook.py — Generate clip_tutorial.ipynb |
| |
| Run this script to produce the tutorial notebook for the CLIP Pelatnas P2 competition. |
| Requires: nbformat (included with jupyter) |
| """ |
|
|
| import nbformat as nbf |
|
|
| nb = nbf.v4.new_notebook() |
| nb.metadata = { |
| "kernelspec": { |
| "display_name": "Python 3", |
| "language": "python", |
| "name": "python3" |
| }, |
| "language_info": { |
| "name": "python", |
| "version": "3.10.0" |
| } |
| } |
|
|
| cells = [] |
|
|
| def md(source): cells.append(nbf.v4.new_markdown_cell(source)) |
| def code(source): cells.append(nbf.v4.new_code_cell(source)) |
|
|
|
|
| |
| |
| |
|
|
| md("""\ |
| # CLIP Tutorial — Pelatnas IOAI 2026 P2 |
| |
| **Topik:** Multimodal Learning — CLIP (Contrastive Language-Image Pretraining) |
| |
| Notebook ini memandu kalian dari nol — memahami arsitektur CLIP, mengimplementasikannya dari scratch, |
| sampai menggunakannya untuk menyelesaikan 4 task kompetisi ARIA. |
| |
| | Section | Topik | |
| |---------|-------| |
| | 1 | CLIP: Arsitektur dan Motivasi | |
| | 2 | Mini CLIP dari Scratch (CIFAR-10) | |
| | 3 | Load Pretrained CLIP + Eksplorasi Embedding Space | |
| | 4 | Zero-Shot Classification | |
| | 5 | Linear Probing | |
| | 6 | Image-Text Retrieval | |
| | 7 | MCQA dengan CLIP | |
| | 8 | Baseline Submission | |
| """) |
|
|
|
|
| |
| |
| |
|
|
| md("""\ |
| --- |
| ## Section 1 — CLIP: Arsitektur dan Motivasi |
| |
| ### Mengapa CLIP? |
| |
| Model vision konvensional (ResNet, ViT) ditraining untuk memprediksi label dari |
| dataset yang fixed (ImageNet → 1000 kelas). Masalahnya: |
| - Tidak bisa generalize ke kelas baru tanpa retraining |
| - Label harus predefined, tidak bisa deskripsi bebas |
| |
| **CLIP** (Contrastive Language-Image Pretraining, Radford et al. 2021) menyelesaikan |
| ini dengan cara berbeda: instead of predicting labels, CLIP belajar *alignment* |
| antara gambar dan teks. |
| |
| ### Dual-Stream Architecture |
| |
| CLIP terdiri dari dua encoder yang ditraining bersama: |
| 1. **Image Encoder**: ViT atau ResNet → menghasilkan image embedding (vektor) |
| 2. **Text Encoder**: Transformer → menghasilkan text embedding (vektor) |
| |
| Kedua encoder memproyeksikan input ke *shared embedding space* dengan dimensi |
| yang sama (e.g., 512 untuk ViT-B/32). |
| |
| ### Training Objective |
| |
| CLIP ditraining dengan dataset **400 juta** pasang (image, caption) dari internet. |
| Objective-nya sederhana: |
| - image dan caption yang **matching** → cosine similarity **TINGGI** |
| - image dan caption yang **tidak matching** → cosine similarity **RENDAH** |
| |
| Ini adalah *contrastive learning*: model belajar "mendekatkan" pasangan yang benar |
| dan "menjauhkan" pasangan yang salah. |
| """) |
|
|
| code("""\ |
| # ── Cell 1.1: Visualisasi konsep similarity matrix ────────────────────────── |
| import numpy as np |
| import matplotlib.pyplot as plt |
| |
| labels = ['cat', 'dog', 'car', 'ship', 'bird', 'horse'] |
| N = len(labels) |
| |
| # Similarity matrix ideal: diagonal tinggi, off-diagonal rendah |
| np.random.seed(42) |
| sim_matrix = np.random.uniform(0.1, 0.4, (N, N)) |
| np.fill_diagonal(sim_matrix, np.random.uniform(0.8, 0.95, N)) |
| |
| fig, ax = plt.subplots(figsize=(7, 6)) |
| im = ax.imshow(sim_matrix, cmap='Blues', vmin=0, vmax=1) |
| ax.set_xticks(range(N)) |
| ax.set_yticks(range(N)) |
| ax.set_xticklabels([f'"{l}"' for l in labels], rotation=45, ha='right') |
| ax.set_yticklabels([f'[IMG {l}]' for l in labels]) |
| ax.set_xlabel('Text Embeddings') |
| ax.set_ylabel('Image Embeddings') |
| ax.set_title('CLIP Similarity Matrix\\n(diagonal = matching pairs)') |
| plt.colorbar(im) |
| |
| for i in range(N): |
| for j in range(N): |
| ax.text(j, i, f'{sim_matrix[i, j]:.2f}', |
| ha='center', va='center', |
| color='white' if sim_matrix[i, j] > 0.6 else 'black', fontsize=9) |
| plt.tight_layout() |
| plt.show() |
| """) |
|
|
|
|
| |
| |
| |
|
|
| md("""\ |
| --- |
| ## Section 2 — Mini CLIP dari Scratch |
| |
| ### Implementasi CLIP dari Nol |
| |
| Kita akan membuat versi miniatur CLIP untuk memahami mekanismenya. |
| Ini **BUKAN** untuk performa — hanya untuk intuisi. |
| |
| Dataset toy: CIFAR-10 subset (1.000 images, 10 classes). |
| Template caption: `"a photo of a {class_name}"`. |
| |
| Komponen yang diperlukan: |
| 1. `TinyImageEncoder`: CNN sederhana → embedding |
| 2. `TinyTextEncoder`: word embedding → pooling → linear |
| 3. `InfoNCE Loss`: fungsi loss contrastive |
| 4. Training loop + visualisasi |
| """) |
|
|
| code("""\ |
| # ── Cell 2.1: Setup dan download CIFAR-10 ─────────────────────────────────── |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
| from torchvision import datasets, transforms |
| from torch.utils.data import DataLoader, Subset |
| import numpy as np |
| |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| print(f"Using device: {device}") |
| |
| CIFAR10_CLASSES = ['airplane', 'automobile', 'bird', 'cat', 'deer', |
| 'dog', 'frog', 'horse', 'ship', 'truck'] |
| |
| transform = transforms.Compose([ |
| transforms.ToTensor(), |
| transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) |
| ]) |
| |
| full_train = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) |
| |
| # Ambil 100 images per class = 1000 total |
| indices_per_class = {c: [] for c in range(10)} |
| for idx, (_, label) in enumerate(full_train): |
| if len(indices_per_class[label]) < 100: |
| indices_per_class[label].append(idx) |
| if all(len(v) == 100 for v in indices_per_class.values()): |
| break |
| |
| all_indices = [idx for idxs in indices_per_class.values() for idx in idxs] |
| toy_labels = [full_train.targets[i] for i in all_indices] |
| toy_dataset = Subset(full_train, all_indices) |
| |
| print(f"Toy dataset size: {len(toy_dataset)} images") |
| """) |
|
|
| code("""\ |
| # ── Cell 2.2: Tiny Image Encoder ──────────────────────────────────────────── |
| class TinyImageEncoder(nn.Module): |
| \"\"\" |
| CNN sederhana: Conv → ReLU → MaxPool (×2) → GAP → Linear projection |
| Input: (B, 3, 32, 32) |
| Output: (B, EMBED_DIM) — normalized embedding |
| \"\"\" |
| def __init__(self, embed_dim=128): |
| super().__init__() |
| self.conv = nn.Sequential( |
| nn.Conv2d(3, 32, kernel_size=3, padding=1), # → (B, 32, 32, 32) |
| nn.ReLU(), |
| nn.MaxPool2d(2), # → (B, 32, 16, 16) |
| nn.Conv2d(32, 64, kernel_size=3, padding=1), # → (B, 64, 16, 16) |
| nn.ReLU(), |
| nn.MaxPool2d(2), # → (B, 64, 8, 8) |
| ) |
| self.projection = nn.Linear(64, embed_dim) |
| |
| def forward(self, x): |
| x = self.conv(x) |
| x = x.mean(dim=[2, 3]) # Global Average Pooling → (B, 64) |
| x = self.projection(x) # (B, embed_dim) |
| return F.normalize(x, dim=-1) # L2-normalize → unit sphere |
| |
| |
| # ── Cell 2.3: Tiny Text Encoder ───────────────────────────────────────────── |
| class TinyTextEncoder(nn.Module): |
| \"\"\" |
| Word embedding → mean pooling → Linear projection |
| Input: token ids (B, seq_len) |
| Output: (B, EMBED_DIM) — normalized embedding |
| \"\"\" |
| def __init__(self, vocab_size, embed_dim=128, hidden_dim=64): |
| super().__init__() |
| self.embedding = nn.Embedding(vocab_size, hidden_dim, padding_idx=0) |
| self.projection = nn.Linear(hidden_dim, embed_dim) |
| |
| def forward(self, x): |
| emb = self.embedding(x) # (B, seq_len, hidden_dim) |
| pooled = emb.mean(dim=1) # mean pooling → (B, hidden_dim) |
| out = self.projection(pooled) |
| return F.normalize(out, dim=-1) |
| """) |
|
|
| code("""\ |
| # ── Cell 2.4: Simple Tokenizer ─────────────────────────────────────────────── |
| templates = [f"a photo of a {c}" for c in CIFAR10_CLASSES] |
| all_words = set() |
| for t in templates: |
| all_words.update(t.split()) |
| vocab = {word: idx + 1 for idx, word in enumerate(sorted(all_words))} |
| vocab['<pad>'] = 0 |
| |
| |
| def tokenize(text, max_len=8): |
| tokens = [vocab.get(w, 0) for w in text.split()] |
| tokens = tokens[:max_len] |
| tokens += [0] * (max_len - len(tokens)) |
| return tokens |
| |
| |
| text_tokens = torch.tensor([tokenize(t) for t in templates]).to(device) # (10, 8) |
| vocab_size = len(vocab) + 1 |
| |
| print("Vocabulary:", vocab) |
| print("Template tokens shape:", text_tokens.shape) |
| """) |
|
|
| code("""\ |
| # ── Cell 2.5: InfoNCE Loss ─────────────────────────────────────────────────── |
| def info_nce_loss(image_emb, text_emb, temperature=0.07): |
| \"\"\" |
| Contrastive loss untuk batch of N image-text pairs. |
| |
| Intuisi: |
| - Hitung similarity matrix N×N |
| - Untuk setiap image, correct text-nya adalah di posisi diagonal |
| - Cross-entropy: dorong diagonal jadi paling tinggi |
| - Loss = rata-rata dua arah (image→text + text→image) |
| \"\"\" |
| logits = (image_emb @ text_emb.T) / temperature # (N, N) |
| labels = torch.arange(len(image_emb)).to(image_emb.device) |
| |
| loss_i2t = F.cross_entropy(logits, labels) |
| loss_t2i = F.cross_entropy(logits.T, labels) |
| |
| return (loss_i2t + loss_t2i) / 2 |
| """) |
|
|
| code("""\ |
| # ── Cell 2.6: TinyCLIP model ──────────────────────────────────────────────── |
| class TinyCLIP(nn.Module): |
| def __init__(self, vocab_size, embed_dim=128): |
| super().__init__() |
| self.image_encoder = TinyImageEncoder(embed_dim) |
| self.text_encoder = TinyTextEncoder(vocab_size, embed_dim) |
| |
| def encode_image(self, images): |
| return self.image_encoder(images) |
| |
| def encode_text(self, tokens): |
| return self.text_encoder(tokens) |
| |
| |
| model = TinyCLIP(vocab_size=vocab_size, embed_dim=128).to(device) |
| print(f"TinyCLIP parameters: {sum(p.numel() for p in model.parameters()):,}") |
| """) |
|
|
| code("""\ |
| # ── Cell 2.7: Training loop ────────────────────────────────────────────────── |
| optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) |
| |
| images_tensor = torch.stack([toy_dataset[i][0] for i in range(len(toy_dataset))]) |
| loader = DataLoader( |
| list(zip(images_tensor, toy_labels)), |
| batch_size=64, shuffle=True |
| ) |
| |
| loss_history = [] |
| NUM_EPOCHS = 10 |
| |
| for epoch in range(NUM_EPOCHS): |
| model.train() |
| epoch_losses = [] |
| |
| for images, labels in loader: |
| images = images.to(device) |
| labels_list = labels.tolist() if isinstance(labels, torch.Tensor) else labels |
| |
| batch_text = text_tokens[labels_list] # (B, 8) |
| image_emb = model.encode_image(images) # (B, 128) |
| text_emb = model.encode_text(batch_text) # (B, 128) |
| |
| loss = info_nce_loss(image_emb, text_emb) |
| |
| optimizer.zero_grad() |
| loss.backward() |
| optimizer.step() |
| |
| epoch_losses.append(loss.item()) |
| |
| mean_loss = np.mean(epoch_losses) |
| loss_history.append(mean_loss) |
| print(f"Epoch {epoch+1:2d}/{NUM_EPOCHS} | Loss: {mean_loss:.4f}") |
| """) |
|
|
| code("""\ |
| # ── Cell 2.8: Plot loss curve ──────────────────────────────────────────────── |
| import matplotlib.pyplot as plt |
| |
| plt.figure(figsize=(8, 4)) |
| plt.plot(range(1, NUM_EPOCHS + 1), loss_history, marker='o', linewidth=2, color='steelblue') |
| plt.xlabel('Epoch') |
| plt.ylabel('InfoNCE Loss') |
| plt.title('TinyCLIP Training Loss') |
| plt.grid(True, alpha=0.3) |
| plt.tight_layout() |
| plt.show() |
| """) |
|
|
| code("""\ |
| # ── Cell 2.9: Visualisasi embedding space (t-SNE) ─────────────────────────── |
| from sklearn.manifold import TSNE |
| |
| model.eval() |
| with torch.no_grad(): |
| all_images = torch.stack([toy_dataset[i][0] for i in range(len(toy_dataset))]).to(device) |
| image_embs = model.encode_image(all_images).cpu().numpy() |
| text_embs = model.encode_text(text_tokens).cpu().numpy() |
| |
| all_embs = np.vstack([image_embs, text_embs]) # (1010, 128) |
| tsne = TSNE(n_components=2, random_state=42, perplexity=30) |
| embs_2d = tsne.fit_transform(all_embs) |
| |
| img_2d = embs_2d[:1000] |
| txt_2d = embs_2d[1000:] |
| |
| colors = plt.cm.tab10(np.linspace(0, 1, 10)) |
| fig, ax = plt.subplots(figsize=(10, 8)) |
| |
| for c in range(10): |
| mask = np.array(toy_labels) == c |
| ax.scatter(img_2d[mask, 0], img_2d[mask, 1], |
| c=[colors[c]], alpha=0.4, s=20, label=CIFAR10_CLASSES[c]) |
| ax.scatter(txt_2d[c, 0], txt_2d[c, 1], |
| c=[colors[c]], marker='*', s=300, edgecolors='black', linewidths=1) |
| |
| ax.legend(loc='upper right', fontsize=8) |
| ax.set_title('t-SNE: TinyCLIP Embedding Space\\n' |
| '(dots = images, stars = text templates)') |
| ax.axis('off') |
| plt.tight_layout() |
| plt.show() |
| """) |
|
|
|
|
| |
| |
| |
|
|
| md("""\ |
| --- |
| ## Section 3 — Load Pretrained CLIP + Eksplorasi Embedding Space |
| |
| ### Dari Scratch ke Pretrained |
| |
| TinyCLIP kita ditraining di 1.000 gambar selama beberapa menit. |
| CLIP asli ditraining di **400 juta** pasang selama berbulan-bulan di ratusan GPU. |
| |
| Hasilnya sangat berbeda. Mari kita load pretrained CLIP dan lihat embedding space-nya. |
| |
| **`openai/clip-vit-b-32`:** |
| - Image encoder: Vision Transformer ViT-B/32 |
| - Text encoder: Transformer 12 layers |
| - Embedding dim: 512 |
| - Total parameters: ~150M |
| """) |
|
|
| code("""\ |
| # ── Cell 3.1: Install dan load CLIP ───────────────────────────────────────── |
| # !pip install git+https://github.com/openai/CLIP.git # jalankan sekali jika belum |
| |
| import clip |
| from PIL import Image |
| import torch |
| import numpy as np |
| import matplotlib.pyplot as plt |
| |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| model_clip, preprocess = clip.load("ViT-B/32", device=device) |
| model_clip.eval() |
| |
| print(f"Model loaded. Input resolution: {model_clip.visual.input_resolution}") |
| print(f"Embedding dimension: {model_clip.visual.output_dim}") |
| """) |
|
|
| code("""\ |
| # ── Cell 3.2: Load STL-10 test images ─────────────────────────────────────── |
| from torchvision import datasets |
| from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize |
| |
| clip_preprocess = Compose([ |
| Resize(224), |
| CenterCrop(224), |
| ToTensor(), |
| Normalize((0.48145466, 0.4578275, 0.40821073), |
| (0.26862954, 0.26130258, 0.27577711)) |
| ]) |
| |
| stl10_test = datasets.STL10(root='./data', split='test', download=True, |
| transform=clip_preprocess) |
| |
| STL10_CLASSES = stl10_test.classes |
| print(f"STL-10 classes: {STL10_CLASSES}") |
| |
| # Ambil 20/class untuk zero-shot (200 total) dan 20/class untuk linear probing (200 total) |
| from collections import defaultdict |
| zs_imgs, zs_labels = [], [] |
| lp_imgs, lp_labels = [], [] |
| zs_count = defaultdict(int) |
| lp_count = defaultdict(int) |
| |
| for idx in range(len(stl10_test)): |
| img, label = stl10_test[idx] |
| if zs_count[label] < 20: |
| zs_imgs.append(img) |
| zs_labels.append(label) |
| zs_count[label] += 1 |
| elif lp_count[label] < 20: |
| lp_imgs.append(img) |
| lp_labels.append(label) |
| lp_count[label] += 1 |
| if sum(zs_count.values()) == 200 and sum(lp_count.values()) == 200: |
| break |
| |
| zs_labels_arr = np.array(zs_labels) |
| lp_test_labels = np.array(lp_labels) |
| print(f"ZS set: {len(zs_imgs)} | LP test set: {len(lp_imgs)}") |
| """) |
|
|
| code("""\ |
| # ── Cell 3.3: Extract CLIP image embeddings ────────────────────────────────── |
| from torch.utils.data import DataLoader, TensorDataset |
| |
| |
| def extract_embeddings(img_list, batch_size=64): |
| \"\"\"Extract CLIP image embeddings dari list of tensors.\"\"\" |
| all_embs = [] |
| for i in range(0, len(img_list), batch_size): |
| batch = torch.stack(img_list[i:i + batch_size]).to(device) |
| with torch.no_grad(): |
| emb = model_clip.encode_image(batch) |
| emb = emb / emb.norm(dim=-1, keepdim=True) |
| all_embs.append(emb.cpu()) |
| return torch.cat(all_embs).numpy() |
| |
| |
| print("Extracting embeddings...") |
| zs_embeddings = extract_embeddings(zs_imgs) |
| lp_test_embeddings = extract_embeddings(lp_imgs) |
| |
| print(f"Zero-shot embeddings: {zs_embeddings.shape}") |
| print(f"Linear probing test embeddings: {lp_test_embeddings.shape}") |
| """) |
|
|
| code("""\ |
| # ── Cell 3.4: Extract text embeddings untuk 10 kelas ──────────────────────── |
| def get_text_embeddings(class_names, template="a photo of a {}"): |
| \"\"\"Encode class names dengan text encoder CLIP.\"\"\" |
| prompts = [template.format(c) for c in class_names] |
| tokens = clip.tokenize(prompts).to(device) |
| with torch.no_grad(): |
| text_emb = model_clip.encode_text(tokens) |
| text_emb = text_emb / text_emb.norm(dim=-1, keepdim=True) |
| return text_emb.cpu().numpy() |
| |
| |
| text_embeddings = get_text_embeddings(STL10_CLASSES) |
| print(f"Text embeddings: {text_embeddings.shape}") # (10, 512) |
| """) |
|
|
| code("""\ |
| # ── Cell 3.5: Visualisasi t-SNE ───────────────────────────────────────────── |
| from sklearn.manifold import TSNE |
| |
| all_embs = np.vstack([zs_embeddings, text_embeddings]) # (210, 512) |
| tsne = TSNE(n_components=2, random_state=42, perplexity=30) |
| embs_2d = tsne.fit_transform(all_embs) |
| |
| img_2d = embs_2d[:200] |
| txt_2d = embs_2d[200:] |
| |
| colors = plt.cm.tab10(np.linspace(0, 1, 10)) |
| fig, ax = plt.subplots(figsize=(12, 9)) |
| |
| for c in range(10): |
| mask = zs_labels_arr == c |
| ax.scatter(img_2d[mask, 0], img_2d[mask, 1], |
| c=[colors[c]], alpha=0.5, s=30, label=STL10_CLASSES[c]) |
| ax.scatter(txt_2d[c, 0], txt_2d[c, 1], |
| c=[colors[c]], marker='*', s=500, edgecolors='black', linewidths=1.5) |
| |
| ax.legend(loc='upper right', fontsize=9) |
| ax.set_title('Pretrained CLIP — Embedding Space (STL-10)\\n' |
| 'Dots = image embeddings | Stars = text template embeddings', fontsize=12) |
| ax.axis('off') |
| plt.tight_layout() |
| plt.show() |
| """) |
|
|
|
|
| |
| |
| |
|
|
| md("""\ |
| --- |
| ## Section 4 — Zero-Shot Classification |
| |
| ### Cara Kerja Zero-Shot dengan CLIP |
| |
| 1. Encode setiap class name menjadi text embedding |
| 2. Encode query image menjadi image embedding |
| 3. Hitung cosine similarity antara image dan semua class embeddings |
| 4. Prediksi = class dengan similarity tertinggi |
| |
| **Prompt engineering penting!** |
| `"dog"` ≠ `"a photo of a dog"` ≠ `"a high-quality photo of a dog, DSLR"` |
| """) |
|
|
| code("""\ |
| # ── Cell 4.1: Zero-shot prediction ────────────────────────────────────────── |
| # zs_embeddings dan text_embeddings sudah dihitung di Section 3 |
| |
| similarity = zs_embeddings @ text_embeddings.T # (200, 10) |
| predictions_idx = np.argmax(similarity, axis=1) |
| predictions_str = [STL10_CLASSES[i] for i in predictions_idx] |
| |
| accuracy = np.mean(predictions_idx == zs_labels_arr) |
| print(f"Zero-shot accuracy: {accuracy:.4f} ({accuracy*100:.1f}%)") |
| """) |
|
|
| code("""\ |
| # ── Cell 4.2: Pengaruh prompt engineering ──────────────────────────────────── |
| templates_to_compare = [ |
| "{}", |
| "a photo of a {}", |
| "a photo of a {}, high quality", |
| "a {} in the wild", |
| ] |
| |
| print("\\nPrompt engineering comparison:") |
| print("-" * 50) |
| for template in templates_to_compare: |
| text_emb = get_text_embeddings(STL10_CLASSES, template) |
| sim = zs_embeddings @ text_emb.T |
| preds = np.argmax(sim, axis=1) |
| acc = np.mean(preds == zs_labels_arr) |
| print(f" {template:<40} → {acc*100:.1f}%") |
| """) |
|
|
| code("""\ |
| # ── Cell 4.3: Confusion matrix ─────────────────────────────────────────────── |
| from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay |
| |
| cm = confusion_matrix(zs_labels_arr, predictions_idx) |
| disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=STL10_CLASSES) |
| |
| fig, ax = plt.subplots(figsize=(10, 8)) |
| disp.plot(ax=ax, colorbar=False, cmap='Blues') |
| ax.set_title('Zero-Shot Classification — Confusion Matrix') |
| plt.xticks(rotation=45, ha='right') |
| plt.tight_layout() |
| plt.show() |
| """) |
|
|
| code("""\ |
| # ── Cell 4.4: Per-class accuracy ───────────────────────────────────────────── |
| per_class_acc = {} |
| for c in range(10): |
| mask = zs_labels_arr == c |
| per_class_acc[STL10_CLASSES[c]] = np.mean(predictions_idx[mask] == c) |
| |
| print("\\nPer-class accuracy:") |
| for cls, acc in sorted(per_class_acc.items(), key=lambda x: -x[1]): |
| bar = '█' * int(acc * 20) |
| print(f" {cls:<10} {acc*100:5.1f}% {bar}") |
| """) |
|
|
|
|
| |
| |
| |
|
|
| md("""\ |
| --- |
| ## Section 5 — Linear Probing |
| |
| ### Perbedaan dari Zero-Shot |
| |
| | Metode | Data berlabel? | Cara prediksi | |
| |--------|---------------|---------------| |
| | Zero-shot | Tidak | Text prompts | |
| | Linear probing | Ya (sedikit) | Classifier di atas frozen embeddings | |
| |
| **Kenapa tidak fine-tune semua layer?** |
| - Linear probing murah secara komputasi |
| - Menguji seberapa "baik" embeddings CLIP tanpa tambahan supervision |
| - Fine-tuning bisa overfit ke domain kecil |
| """) |
|
|
| code("""\ |
| # ── Cell 5.1: Extract train embeddings untuk linear probing ───────────────── |
| stl10_train = datasets.STL10(root='./data', split='train', download=True, |
| transform=clip_preprocess) |
| |
| # Ambil 100/class = 1000 images untuk training |
| train_imgs, train_labels = [], [] |
| count = defaultdict(int) |
| |
| for idx in range(len(stl10_train)): |
| img, label = stl10_train[idx] |
| if count[label] < 100: |
| train_imgs.append(img) |
| train_labels.append(label) |
| count[label] += 1 |
| if sum(count.values()) == 1000: |
| break |
| |
| train_labels_arr = np.array(train_labels) |
| print("Extracting train embeddings...") |
| lp_train_embeddings = extract_embeddings(train_imgs) |
| print(f"Train embeddings: {lp_train_embeddings.shape}") |
| """) |
|
|
| code("""\ |
| # ── Cell 5.2: Train classifier ─────────────────────────────────────────────── |
| from sklearn.linear_model import LogisticRegression |
| |
| clf = LogisticRegression(max_iter=1000, C=0.316, random_state=42) |
| clf.fit(lp_train_embeddings, train_labels_arr) |
| |
| lp_predictions = clf.predict(lp_test_embeddings) |
| lp_accuracy = np.mean(lp_predictions == lp_test_labels) |
| print(f"Linear probing accuracy: {lp_accuracy:.4f} ({lp_accuracy*100:.1f}%)") |
| """) |
|
|
| code("""\ |
| # ── Cell 5.3: Perbandingan zero-shot vs linear probing ─────────────────────── |
| print("\\n" + "="*50) |
| print(" Perbandingan: Zero-Shot vs Linear Probing") |
| print("="*50) |
| print(f" Zero-shot (0 training images) : {accuracy*100:5.1f}%") |
| print(f" Linear probe (1.000 labeled imgs) : {lp_accuracy*100:5.1f}%") |
| print(f" Gap: +{(lp_accuracy - accuracy)*100:.1f}%") |
| print("="*50) |
| """) |
|
|
| code("""\ |
| # ── Cell 5.4: Bar chart per-class comparison ───────────────────────────────── |
| per_class_lp = {} |
| for c in range(10): |
| mask = lp_test_labels == c |
| per_class_lp[STL10_CLASSES[c]] = np.mean(lp_predictions[mask] == c) |
| |
| fig, ax = plt.subplots(figsize=(12, 5)) |
| x = np.arange(10) |
| w = 0.35 |
| zs_vals = [per_class_acc[c] for c in STL10_CLASSES] |
| lp_vals = [per_class_lp[c] for c in STL10_CLASSES] |
| |
| ax.bar(x - w/2, zs_vals, w, label='Zero-shot', color='steelblue', alpha=0.8) |
| ax.bar(x + w/2, lp_vals, w, label='Linear probe', color='coral', alpha=0.8) |
| ax.set_xticks(x) |
| ax.set_xticklabels(STL10_CLASSES, rotation=45, ha='right') |
| ax.set_ylabel('Accuracy') |
| ax.set_title('Per-Class Accuracy: Zero-Shot vs Linear Probing') |
| ax.legend() |
| ax.set_ylim(0, 1.05) |
| ax.grid(True, axis='y', alpha=0.3) |
| plt.tight_layout() |
| plt.show() |
| """) |
|
|
|
|
| |
| |
| |
|
|
| md("""\ |
| --- |
| ## Section 6 — Image-Text Retrieval |
| |
| ### Retrieval sebagai Task Matching |
| |
| CLIP sangat natural untuk retrieval: |
| 1. Encode query image → image embedding |
| 2. Encode semua candidate captions → text embeddings |
| 3. Similarity = cosine similarity |
| 4. Predict = candidate dengan similarity tertinggi |
| |
| Dalam competition: **4 candidates per query**, predict index 0–3. |
| """) |
|
|
| code("""\ |
| # ── Cell 6.1: Load Flickr8k test data ──────────────────────────────────────── |
| import pandas as pd |
| from PIL import Image as PILImage |
| |
| DATASET_ROOT = '/kaggle/input/clip-pelatnas-p2' |
| candidates_df = pd.read_csv(f'{DATASET_ROOT}/test/retrieval/candidates.csv') |
| print(f"Retrieval test: {len(candidates_df)} queries") |
| print(candidates_df.head(2)) |
| """) |
|
|
| code("""\ |
| # ── Cell 6.2: CLIP retrieval pipeline ──────────────────────────────────────── |
| def clip_retrieval(image_path, captions, model, preprocess, device): |
| \"\"\" |
| Predict correct caption index untuk satu query. |
| Returns: (predicted_idx, similarities_array) |
| \"\"\" |
| image = preprocess(PILImage.open(image_path)).unsqueeze(0).to(device) |
| with torch.no_grad(): |
| img_emb = model.encode_image(image) |
| img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True) |
| |
| tokens = clip.tokenize(captions, truncate=True).to(device) |
| with torch.no_grad(): |
| txt_emb = model.encode_text(tokens) |
| txt_emb = txt_emb / txt_emb.norm(dim=-1, keepdim=True) |
| |
| similarities = (img_emb @ txt_emb.T).squeeze().cpu().numpy() |
| predicted_idx = int(np.argmax(similarities)) |
| return predicted_idx, similarities |
| """) |
|
|
| code("""\ |
| # ── Cell 6.3: Batch evaluation ──────────────────────────────────────────────── |
| base_path = f'{DATASET_ROOT}/test/retrieval/queries/' |
| predictions_ret = [] |
| |
| for _, row in candidates_df.iterrows(): |
| captions = [row[f'caption_{i}'] for i in range(4)] |
| pred_idx, _ = clip_retrieval( |
| base_path + row['image_path'], captions, model_clip, preprocess, device |
| ) |
| predictions_ret.append(pred_idx) |
| |
| predictions_ret = np.array(predictions_ret) |
| correct_idx = candidates_df['correct_idx'].values |
| |
| ret_accuracy = np.mean(predictions_ret == correct_idx) |
| print(f"Retrieval accuracy (4-way): {ret_accuracy:.4f} ({ret_accuracy*100:.1f}%)") |
| print(f"Random baseline: 25.0%") |
| """) |
|
|
| code("""\ |
| # ── Cell 6.4: Qualitative examples ─────────────────────────────────────────── |
| fig, axes = plt.subplots(2, 4, figsize=(16, 7)) |
| correct_mask = predictions_ret == correct_idx |
| correct_examples = np.where(correct_mask)[0][:2] |
| wrong_examples = np.where(~correct_mask)[0][:2] |
| examples = list(correct_examples) + list(wrong_examples) |
| |
| for col, idx in enumerate(examples): |
| row_data = candidates_df.iloc[idx] |
| captions = [row_data[f'caption_{i}'] for i in range(4)] |
| _, sims = clip_retrieval( |
| base_path + row_data['image_path'], captions, model_clip, preprocess, device |
| ) |
| |
| img = PILImage.open(base_path + row_data['image_path']) |
| axes[0, col].imshow(img) |
| axes[0, col].set_title('Benar' if col < 2 else 'Salah', |
| color='green' if col < 2 else 'red', fontsize=12) |
| axes[0, col].axis('off') |
| |
| for i, (cap, sim) in enumerate(zip(captions, sims)): |
| is_correct = (i == row_data['correct_idx']) |
| is_wrong = (i == predictions_ret[idx] and not is_correct) |
| color = 'green' if is_correct else ('red' if is_wrong else 'black') |
| marker = '★' if is_correct else ('✗' if is_wrong else ' ') |
| axes[1, col].text(0.02, 0.88 - i * 0.23, |
| f"{marker} [{sim:.2f}] {cap[:55]}...", |
| transform=axes[1, col].transAxes, |
| fontsize=7, color=color) |
| axes[1, col].axis('off') |
| |
| plt.suptitle('Retrieval Examples (★ = correct answer, ✗ = wrong prediction)', fontsize=12) |
| plt.tight_layout() |
| plt.show() |
| """) |
|
|
|
|
| |
| |
| |
|
|
| md("""\ |
| --- |
| ## Section 7 — MCQA dengan CLIP |
| |
| ### Keterbatasan CLIP untuk Reasoning |
| |
| Cara naive dengan CLIP: |
| - Encode image |
| - Untuk setiap pilihan jawaban: encode `"Question: {q} Answer: {choice}"` |
| - Predict = pilihan dengan similarity tertinggi terhadap image |
| |
| **Limitation**: CLIP tidak didesain untuk reasoning bertahap. |
| CLIP bagus di *"apa yang ada di gambar ini?"* tapi terbatas untuk |
| *"kenapa hal ini terjadi?"* atau soal sains yang butuh domain knowledge. |
| """) |
|
|
| code("""\ |
| # ── Cell 7.1: Load ScienceQA test data ────────────────────────────────────── |
| mcqa_df = pd.read_csv(f'{DATASET_ROOT}/test/mcqa/test.csv') |
| print(f"MCQA test: {len(mcqa_df)} questions") |
| print(mcqa_df.head(2)) |
| """) |
|
|
| code("""\ |
| # ── Cell 7.2: CLIP MCQA pipeline ───────────────────────────────────────────── |
| def clip_mcqa(image_path, question, choices, model, preprocess, device): |
| \"\"\" |
| Predict correct answer untuk MCQA. |
| Strategi: encode image, bandingkan dengan "Question: {q} Answer: {choice}". |
| \"\"\" |
| image = preprocess(PILImage.open(image_path)).unsqueeze(0).to(device) |
| with torch.no_grad(): |
| img_emb = model.encode_image(image) |
| img_emb = img_emb / img_emb.norm(dim=-1, keepdim=True) |
| |
| texts = [f"Question: {question} Answer: {c}" for c in choices] |
| tokens = clip.tokenize(texts, truncate=True).to(device) |
| with torch.no_grad(): |
| txt_emb = model.encode_text(tokens) |
| txt_emb = txt_emb / txt_emb.norm(dim=-1, keepdim=True) |
| |
| similarities = (img_emb @ txt_emb.T).squeeze().cpu().numpy() |
| predicted_idx = int(np.argmax(similarities)) |
| |
| letter_map = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'} |
| return letter_map[predicted_idx], similarities |
| """) |
|
|
| code("""\ |
| # ── Cell 7.3: Batch evaluation ──────────────────────────────────────────────── |
| base_path_mcqa = f'{DATASET_ROOT}/test/mcqa/images/' |
| predictions_mcqa = [] |
| |
| for _, row in mcqa_df.iterrows(): |
| n_choices = int(row['num_choices']) |
| choices = [row[f'choice_{chr(65+i)}'] for i in range(n_choices)] |
| |
| pred_letter, _ = clip_mcqa( |
| base_path_mcqa + row['image_path'], |
| row['question'], choices, model_clip, preprocess, device |
| ) |
| predictions_mcqa.append(pred_letter) |
| |
| mcqa_accuracy = np.mean(np.array(predictions_mcqa) == mcqa_df.get('answer', pd.Series([])).values) \ |
| if 'answer' in mcqa_df.columns else float('nan') |
| |
| print(f"MCQA accuracy: {mcqa_accuracy:.4f} ({mcqa_accuracy*100:.1f}%)" if not np.isnan(mcqa_accuracy) |
| else "MCQA predictions done (answer column not available in test set)") |
| print(f"Random baseline (~3.5 choices avg): ~{100/3.5:.1f}%") |
| """) |
|
|
| code("""\ |
| # ── Cell 7.4: Analysis per subject ─────────────────────────────────────────── |
| mcqa_df_copy = mcqa_df.copy() |
| mcqa_df_copy['predicted'] = predictions_mcqa |
| |
| if 'subject' in mcqa_df_copy.columns and 'answer' in mcqa_df_copy.columns: |
| mcqa_df_copy['correct'] = mcqa_df_copy['predicted'] == mcqa_df_copy['answer'] |
| subject_acc = mcqa_df_copy.groupby('subject')['correct'].mean().sort_values(ascending=False) |
| |
| print("Accuracy per subject:") |
| for subj, acc in subject_acc.items(): |
| bar = '█' * int(acc * 20) |
| print(f" {subj:<25} {acc*100:5.1f}% {bar}") |
| else: |
| subj_counts = mcqa_df_copy.groupby('subject')['predicted'].count() |
| print("Question count per subject:") |
| for subj, cnt in subj_counts.items(): |
| print(f" {subj:<25} {cnt} questions") |
| """) |
|
|
|
|
| |
| |
| |
|
|
| md("""\ |
| --- |
| ## Section 8 — Baseline Submission |
| |
| ### Membuat Submission |
| |
| Kode berikut menggabungkan prediksi dari semua 4 task ke dalam satu CSV. |
| Ini adalah baseline paling sederhana: semua task menggunakan zero-shot CLIP. |
| |
| **Estimasi skor baseline: ~70–80% overall accuracy.** |
| |
| Cara improve: |
| - Prompt engineering yang lebih baik |
| - Gunakan model CLIP yang lebih besar (ViT-L/14) |
| - Fine-tuning CLIP untuk task tertentu |
| - Ensemble dengan model multimodal lain (BLIP, SigLIP) |
| """) |
|
|
| code("""\ |
| # ── Cell 8.1: Compile semua prediksi ───────────────────────────────────────── |
| import pandas as pd |
| |
| sample_sub = pd.read_csv(f'{DATASET_ROOT}/sample_submission.csv') |
| pred_map = {} |
| |
| # Zero-shot predictions (dari Section 4) |
| zs_ids = [f'zs_{i:04d}' for i in range(1, 201)] |
| for id_, pred in zip(zs_ids, predictions_str): |
| pred_map[id_] = pred |
| |
| # Linear probing predictions (dari Section 5) |
| lp_ids = [f'lp_{i:04d}' for i in range(1, 201)] |
| lp_cls_str = [STL10_CLASSES[p] for p in lp_predictions] |
| for id_, pred in zip(lp_ids, lp_cls_str): |
| pred_map[id_] = pred |
| |
| # Retrieval predictions (dari Section 6) |
| for id_, pred in zip(candidates_df['id'].values, predictions_ret.tolist()): |
| pred_map[id_] = int(pred) |
| |
| # MCQA predictions (dari Section 7) |
| for id_, pred in zip(mcqa_df['id'].values, predictions_mcqa): |
| pred_map[id_] = pred |
| """) |
|
|
| code("""\ |
| # ── Cell 8.2: Generate submission ──────────────────────────────────────────── |
| submission = sample_sub.copy() |
| submission['prediction'] = submission['id'].map(pred_map) |
| |
| assert len(submission) == 800, f"Expected 800 rows, got {len(submission)}" |
| assert submission['prediction'].isna().sum() == 0, "Ada id yang tidak terprediksi!" |
| |
| print("Submission preview (2 per task):") |
| for prefix in ['zs', 'lp', 'ret', 'mcqa']: |
| mask = submission['id'].str.startswith(prefix) |
| print(submission[mask].head(2).to_string(index=False)) |
| print() |
| |
| submission.to_csv('submission.csv', index=False) |
| print(f"Saved: submission.csv ({len(submission)} rows)") |
| """) |
|
|
| code("""\ |
| # ── Cell 8.3: Sanity check ──────────────────────────────────────────────────── |
| print("Distribusi prediksi per task:\\n") |
| for prefix, name in [('zs', 'Zero-shot'), ('lp', 'Linear probe'), |
| ('ret', 'Retrieval'), ('mcqa', 'MCQA')]: |
| mask = submission['id'].str.startswith(prefix) |
| subset = submission[mask] |
| counts = subset['prediction'].value_counts().to_dict() |
| print(f" {name} ({mask.sum()} items): {counts}") |
| """) |
|
|
|
|
| |
| |
| |
|
|
| nb.cells = cells |
|
|
| with open('clip_tutorial.ipynb', 'w', encoding='utf-8') as f: |
| nbf.write(nb, f) |
|
|
| print("clip_tutorial.ipynb created successfully!") |
| print(f"Cells: {len(cells)} total") |
|
|