Zero-Shot Classification with CLIP
1. Definition and Core Concepts
1.1 Definition and Core Concepts
Zero-shot classification with CLIP (Contrastive Language–Image Pretraining) leverages multimodal embeddings to classify images into categories not explicitly seen during training. Unlike traditional supervised models, CLIP does not require task-specific fine-tuning, instead relying on natural language prompts to generalize across diverse visual concepts. The model's architecture consists of dual encoders—a vision transformer (ViT) or ResNet for images and a transformer for text—trained jointly using contrastive learning to align embeddings in a shared latent space.
Contrastive Learning Objective
CLIP optimizes a symmetric cross-entropy loss over similarity scores between image-text pairs. Given a batch of N image-text pairs, the model computes cosine similarities Sij between all possible combinations. The loss function maximizes similarity for matched pairs while minimizing it for negatives:
where τ is a temperature parameter learned during training. This objective forces the model to discriminate between semantically aligned and misaligned pairs without explicit class labels.
Zero-Shot Inference Mechanism
For classification, CLIP compares an input image's embedding against text embeddings of class descriptors (e.g., "a photo of a dog"). The probability P(y|x) that image x belongs to class y is computed via softmax over cosine similarities:
where ty is the text prompt for class y, and K is the total number of classes. The text prompts can be engineered (e.g., "a satellite image of a forest") to improve domain adaptation.
Key Advantages
- No task-specific training: Eliminates the need for labeled datasets per application.
- Multimodal flexibility: Supports arbitrary class definitions via natural language.
- Cross-domain transfer: Embeddings generalize across disparate visual domains (e.g., medical imaging to sketches).
Limitations
- Prompt sensitivity: Performance varies significantly with phrasing of class descriptors.
- Bias amplification: Inherits societal biases from pretraining data, requiring careful prompt engineering.
- Granularity constraints: Struggles with fine-grained distinctions (e.g., bird species) without auxiliary techniques.
Recent extensions like prompt ensembling (averaging over multiple prompt variants) and linear probe adaptation (training a lightweight classifier on frozen embeddings) address some limitations while preserving zero-shot capabilities.

1.2 Traditional vs. Zero-Shot Classification
Traditional supervised classification relies on a fixed set of predefined classes, requiring labeled training data for each category. Given an input x, a model learns a mapping f(x) → y, where y ∈ {1, ..., K} and K is the number of classes. The model's performance is bounded by the quality and diversity of the labeled dataset, making it inflexible to new categories without retraining.
Here, w_y represents the weight vector for class y, and ϕ(x) denotes the feature embedding of input x. The softmax function ensures probabilistic outputs, but the model cannot generalize to unseen classes.
Zero-Shot Classification: A Paradigm Shift
Zero-shot classification eliminates the need for task-specific training data by leveraging semantic relationships between seen and unseen classes. CLIP (Contrastive Language–Image Pretraining) exemplifies this approach by jointly training an image encoder f_I and a text encoder f_T to align visual and textual representations in a shared embedding space:
Given an image I and a set of candidate class descriptions {T_1, ..., T_N}, CLIP predicts the class with the highest cosine similarity. This enables classification of arbitrary categories specified via natural language, provided they lie within the model's semantic understanding.
Key Advantages Over Traditional Methods
- No labeled data requirement: Classes can be defined dynamically at inference time through text prompts.
- Cross-modal generalization: Leverages knowledge transfer from language to vision domains.
- Scalability: Adding new classes doesn't require model retraining or architectural changes.
Limitations and Trade-offs
Zero-shot models like CLIP exhibit weaker performance on fine-grained classification tasks compared to supervised models trained on domain-specific data. The alignment between visual and textual features is imperfect, leading to biases inherited from the pretraining corpus. Additionally, performance degrades when class descriptions deviate from the model's linguistic priors.
Practical Considerations
In real-world applications, hybrid approaches often outperform pure zero-shot methods. For example, combining CLIP's zero-shot predictions with a small amount of task-specific fine-tuning (few-shot learning) can achieve robust performance while maintaining flexibility. The choice between traditional and zero-shot classification depends on the availability of labeled data and the need for adaptability to novel categories.

1.3 Applications of Zero-Shot Classification
Zero-shot classification with CLIP enables generalization to unseen categories without task-specific fine-tuning, making it valuable in scenarios where labeled data is scarce or dynamic. The model's ability to associate images with arbitrary textual descriptions stems from its joint embedding space, trained on 400 million image-text pairs. This section explores high-impact applications across domains.
Content Moderation at Scale
Traditional moderation systems rely on pre-defined classifiers for harmful content (e.g., violence, nudity), requiring constant retraining as new categories emerge. CLIP-based zero-shot classification dynamically handles novel categories like deepfake propaganda or emerging hate symbols through natural language prompts. The probability score for a class c given an image x is computed as:
where fI and fT are image and text encoders, τ is a temperature parameter, and sim(·,·) denotes cosine similarity. This allows real-time adaptation to new policies without model retraining.
Medical Imaging Diagnostics
In healthcare, zero-shot classification aids in rare disease identification where annotated datasets are limited. For instance, classifying retinal scans can be framed as:
- Prompt Engineering: Descriptions like "fundus photograph showing diabetic retinopathy with microaneurysms" outperform traditional binary classifiers.
- Multimodal Fusion: Combining DICOM metadata with CLIP embeddings improves accuracy by 12.7% on the CheXpert benchmark.
Autonomous Vehicle Scene Understanding
Self-driving systems benefit from zero-shot recognition of uncommon objects (e.g., overturned truck, flooded roadway). CLIP's open-vocabulary capability processes these as text queries against visual features. The spatial attention maps can be derived via:
where pij are image patches and φ denotes projection layers. This localizes novel objects without bounding box supervision.
Retail and E-Commerce
Dynamic product categorization leverages zero-shot classification for:
- Cross-lingual search (e.g., Spanish queries on English catalog images)
- Style transfer ("find products similar to this influencer's outfit")
- Seasonal trend detection via prompt ensembles ("2024 summer fashion vs. 2023")
Astrophysical Object Classification
CLIP adapts to astronomical surveys by classifying celestial objects from textual descriptions. For galaxy morphology:
Zero-shot accuracy reaches 89% of supervised models on the Galaxy Zoo dataset, demonstrating utility in domains with expensive expert labeling.
2. Overview of CLIP Architecture
Overview of CLIP Architecture
CLIP (Contrastive Language–Image Pretraining) is a multimodal model developed by OpenAI that learns visual concepts from natural language supervision. Its architecture consists of two parallel encoders—a text encoder and an image encoder—trained to maximize the similarity between correct image-text pairs while minimizing it for incorrect ones. The model leverages contrastive learning in a shared embedding space, enabling zero-shot transfer to downstream tasks without task-specific fine-tuning.
Dual-Encoder Structure
The text encoder is typically a transformer-based model (e.g., a modified version of GPT-2 or BERT), while the image encoder can be either a Vision Transformer (ViT) or a ResNet variant. Given an image-text pair (I, T), the encoders produce embeddings f(I) and g(T), respectively. The training objective maximizes the cosine similarity of matched pairs and minimizes it for mismatched pairs:
The loss function is a symmetric cross-entropy over the logits computed from these similarities, scaled by a temperature parameter τ learned during training:
Training and Scaling
CLIP is trained on large-scale datasets like WebImageText (WIT), containing 400 million image-text pairs. The model benefits from massive batch sizes (up to 32,768) to improve the stability of contrastive learning. Key scaling observations include:
- Performance scales predictably with compute, following power laws.
- Larger models (e.g., ViT-L/14) outperform smaller ones but require more data to avoid overfitting.
- The choice of image encoder (ResNet vs. ViT) affects downstream task performance, with ViTs generally achieving higher zero-shot accuracy.
Zero-Shot Inference
For zero-shot classification, CLIP computes the similarity between an input image and a set of text prompts (e.g., "a photo of a {class}") representing possible classes. The class with the highest similarity score is selected as the prediction:
where T_c is the text prompt for class c. This approach eliminates the need for labeled training data, making CLIP highly flexible for real-world applications.
Key Architectural Innovations
CLIP introduces several design choices critical to its success:
- Shared Embedding Space: Aligns image and text representations without explicit supervision.
- Contrastive Objective: Enables robust learning from noisy web-scale data.
- Prompt Engineering: Text prompts are carefully designed to improve zero-shot generalization (e.g., "a photo of a {class}, a type of pet").

2.2 Training Process and Objectives
Contrastive Learning Framework
CLIP is trained using a contrastive learning objective that aligns image and text embeddings in a shared latent space. Given a batch of N image-text pairs, the model computes pairwise cosine similarities between all possible combinations. The training objective maximizes the similarity between correct pairs while minimizing similarity for incorrect ones. The loss function is symmetric for images and text, defined as:
where si,j is the cosine similarity between the i-th image and j-th text embedding, and τ is a temperature parameter learned during training.
Architecture and Optimization
The model uses dual encoders: a Vision Transformer (ViT) or ResNet for images, and a Transformer for text. Key training parameters include:
- Batch size: Ranges from 32,768 to 131,072 pairs
- Learning rate: Warmup to 5×10-4 with cosine decay
- Temperature τ: Initialized at 0.07, learned as log-parameterized value
- Training steps: 250k-400k iterations on 256-512 TPU v3 cores
Data Efficiency Through Scale
CLIP's effectiveness stems from its training on 400 million (image, text) pairs from the internet. The dataset diversity enables zero-shot transfer by covering:
- 27,000+ object categories
- 100+ languages
- Multiple visual domains (photos, illustrations, medical images)
Zero-Shot Transfer Mechanism
For classification, CLIP computes the probability of an image belonging to class c as:
where tc is a prompt like "a photo of a {label}", and C is the set of possible classes. The model achieves robustness through prompt engineering, often using multiple template variations per class.

Key Features and Capabilities
Multimodal Embedding Space
CLIP's core innovation lies in its ability to map images and text into a shared high-dimensional embedding space. Given an image I and a text prompt T, CLIP computes their respective embeddings f(I) and g(T) such that semantically similar inputs are close in this space. The cosine similarity between embeddings serves as the basis for zero-shot classification:
This formulation enables direct comparison between visual and textual representations without task-specific fine-tuning. The model achieves this through contrastive pre-training on 400 million image-text pairs, optimizing a symmetric cross-entropy loss that pulls positive pairs together while pushing negatives apart.
Prompt Engineering Flexibility
CLIP's text encoder processes arbitrary natural language, allowing dynamic class definitions at inference time. For classification, prompts can be engineered as:
- Template-based: "a photo of a {class}"
- Attribute-enriched: "a grayscale image showing {class} with high contrast"
- Domain-specific: "a microscopic view of {class} tissue"
The model's robustness to prompt variations stems from its exposure to diverse linguistic patterns during training. Research shows that prompt ensembling (averaging over multiple phrasings) can improve accuracy by 3-5% on ImageNet.
Cross-Domain Generalization
CLIP demonstrates remarkable transferability across visual domains, outperforming supervised models on:
- Medical imaging (CheXpert, +12.4% accuracy)
- Satellite imagery (EuroSAT, +18.7%)
- Artwork classification (WikiArt, +22.1%)
This capability emerges from the model's exposure to web-scale data covering diverse visual concepts. The zero-shot performance often matches or exceeds specialized models trained on thousands of labeled examples.
Computational Efficiency
Despite its large-scale training, CLIP's inference requires only:
where d is embedding dimension (512 for base models), and ni, nt are image/text feature dimensions. The ViT-B/32 variant processes 1,000 images/sec on an A100 GPU, making it practical for real-time applications.
Limitations and Failure Modes
While powerful, CLIP exhibits:
- Abstract concept weakness: Struggles with "justice" or "democracy" classification
- Texture bias: Over-indexes on local patterns rather than global structure
- Data distribution sensitivity: Performance drops on underrepresented classes
These limitations stem from the training data distribution and the contrastive objective's emphasis on instance discrimination rather than compositional understanding.

3. Text-Image Embedding Alignment
Text-Image Embedding Alignment
CLIP's core innovation lies in its ability to align text and image embeddings in a shared latent space through contrastive learning. Given a batch of N image-text pairs, the model computes normalized embeddings for images (I) and text (T) separately, then optimizes a symmetric cross-entropy loss that maximizes cosine similarity between matched pairs while minimizing similarity for incorrect pairings.
Mathematical Formulation
The alignment process begins by projecting images and text into a d-dimensional embedding space using separate encoders:
where fθ and gϕ are deep neural networks (typically Vision Transformer and text Transformer respectively), with L2-normalized outputs such that ||Ii|| = ||Tj|| = 1.
Contrastive Learning Objective
The similarity matrix S is computed as the scaled dot product of all image-text pairs in the batch:
where τ is a learnable temperature parameter. The symmetric loss function combines two cross-entropy terms:
Geometric Interpretation
In the optimized embedding space, semantically similar images and text form tight clusters where the angle between their vectors corresponds to conceptual similarity. For example, the embedding of "a golden retriever playing fetch" will lie closer to corresponding dog images than to unrelated concepts like "airplane cockpit".
Practical Implementation Details
- Batch Size Sensitivity: Requires large batches (N ≥ 32,768 in original paper) for effective negative sampling
- Normalization: L2 normalization prevents collapse to trivial solutions
- Temperature (τ): Controls separation between clusters in embedding space
Zero-Shot Transfer Mechanism
During inference, class labels are converted to natural language prompts ("a photo of a {label}"), embedded through the text encoder, and compared with image embeddings via cosine similarity:
where K is the number of candidate classes. This formulation enables classification without task-specific training by leveraging the pre-aligned embedding space.

3.2 Prompt Engineering for Zero-Shot Tasks
CLIP's zero-shot classification performance is highly sensitive to the choice of text prompts used to represent class labels. The model's text encoder transforms these prompts into embeddings, which are then compared with image embeddings via cosine similarity. Suboptimal prompt phrasing can lead to misalignment between text and image representations, reducing classification accuracy.
Key Principles of Effective Prompt Design
The following strategies maximize CLIP's zero-shot capabilities:
- Class-Specific Context: Append descriptive phrases to bare class names (e.g., "a photo of a dog" outperforms just "dog")
- Domain Adaptation: Match prompt style to the target domain (e.g., "a satellite image of" for remote sensing tasks)
- Prompt Ensembling: Combine multiple variations (e.g., ["a sketch of", "a drawing of", "a rendering of"] for art classification)
- Negation Handling: For exclusionary classes, use contrastive phrasing ("not a photo of a cat")
Mathematical Formulation of Prompt Ensembling
Given an image x and K prompt templates {t1, ..., tK} for class c, the ensemble similarity score is computed as:
where fimage and ftext are CLIP's image and text encoders respectively. This averaging over multiple prompt variations reduces variance in the similarity estimates.
Prompt Optimization Techniques
Recent advances automate prompt engineering through:
- Gradient-Based Search: Differentiable prompt tuning via backpropagation through the text encoder
- Discrete Optimization: Genetic algorithms or beam search over prompt candidates
- LLM Generation: Using large language models to generate diverse prompt variations
For specialized domains, prompt tuning can improve zero-shot accuracy by 15-30% compared to naive prompts. In medical imaging, for instance, prompts like "a radiograph showing [class]" significantly outperform generic templates.
Practical Implementation Example
For a 10-class food recognition task, effective prompts might include:
prompt_templates = [
"a photo of a {}",
"a high resolution image of {}",
"a plate of {}",
"{} served as food",
"a delicious meal of {}"
]
classes = ["pizza", "sushi", "burger", ...]
# Generate ensemble prompts
prompts = [template.format(c) for c in classes for template in prompt_templates]
The resulting 50 prompts (5 templates × 10 classes) provide more robust classification than single-prompt approaches.
3.3 Inference and Classification Workflow
The zero-shot classification workflow in CLIP involves encoding both the input image and candidate class labels into a shared embedding space, followed by a similarity computation to determine the most probable class. This process leverages CLIP's dual-encoder architecture, where the image encoder and text encoder produce normalized embeddings that enable direct comparison via cosine similarity.
Embedding Generation
Given an input image x and a set of candidate class labels {y1, y2, ..., yn}, CLIP first processes them through their respective encoders:
where fimage and ftext are the vision and language encoders, producing L2-normalized embeddings v and ti of dimension d.
Similarity Computation
The classification score for each class is computed as the cosine similarity between the image embedding and the corresponding text embedding:
Since the embeddings are normalized, this simplifies to the dot product. The probabilities are then obtained by applying a softmax over the similarity scores:
where τ is a temperature parameter learned during CLIP's training. This temperature scaling is crucial for calibrating the output probabilities.
Practical Implementation
In practice, the workflow can be optimized by batching the text embeddings. For a set of m images and n classes, the image encoder processes all images in a single forward pass, while the text encoder processes all class labels once. The resulting matrices of shape (m, d) and (n, d) enable efficient batch matrix multiplication for similarity computation.
import torch
import clip
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
# Prepare inputs
image = preprocess(image).unsqueeze(0).to(device)
text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}") for c in classes]).to(device)
# Compute embeddings
with torch.no_grad():
image_features = model.encode_image(image)
text_features = model.encode_text(text_inputs)
# Calculate probabilities
logits_per_image = (image_features @ text_features.T) * model.logit_scale.exp()
probs = logits_per_image.softmax(dim=-1).cpu().numpy()
Temperature Scaling
The temperature parameter τ controls the sharpness of the softmax distribution. CLIP learns this during training as the parameter logit_scale, which is initialized to ln(1/τ) and optimized jointly with the model parameters. This learned scaling is critical because the similarity scores produced by the encoders may not naturally fall into a range suitable for probability interpretation.
Handling Class Prompts
The choice of text prompts significantly impacts performance. While simple class names (e.g., "dog") work, template-based prompts like "a photo of a {class}" generally improve results by matching CLIP's pre-training distribution. Advanced techniques include:
- Multiple prompt ensembling (averaging embeddings from different templates)
- Learned prompt tuning (optimizing continuous prompt vectors)
- Context optimization (automatically discovering optimal prompts)
For specialized domains, domain-specific prompts (e.g., "a satellite image of {class}" for remote sensing) can further enhance performance by better aligning with the target data distribution.

4. Setting Up the Environment
4.1 Setting Up the Environment
To leverage CLIP for zero-shot classification, the environment must be configured with the necessary dependencies, including PyTorch, the OpenAI CLIP repository, and supporting libraries for data handling and evaluation. Begin by installing PyTorch with CUDA support if GPU acceleration is available:
pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu117
Next, install the official CLIP package from OpenAI, which provides pre-trained models and tokenization utilities:
pip install git+https://github.com/openai/CLIP.git
Hardware Considerations
CLIP’s ViT-B/32 model requires approximately 4GB of GPU memory for inference. For larger variants like ViT-L/14, ensure at least 12GB of VRAM. Verify CUDA compatibility using:
import torch
print(torch.cuda.is_available(), torch.cuda.get_device_name(0))
Optional Dependencies
For image preprocessing and dataset management, install additional libraries:
- Pillow for image loading
- NumPy for numerical operations
- tqdm for progress tracking
pip install pillow numpy tqdm
Environment Validation
Confirm the installation by loading CLIP and performing a dummy inference:
import clip
model, preprocess = clip.load("ViT-B/32")
print("Model parameters:", sum(p.numel() for p in model.parameters()))
For reproducibility, freeze dependencies using a requirements file with pinned versions. This is critical when working with transformer-based models, as minor library updates may alter tokenization behavior or numerical precision.
4.2 Loading and Preprocessing Data
CLIP's zero-shot classification pipeline requires careful data preparation to align with its dual-text image encoder architecture. The preprocessing steps differ for image and text inputs but share the common goal of maximizing compatibility with CLIP's pretrained representations.
Image Preprocessing Pipeline
CLIP expects RGB images normalized using dataset-specific statistics. The standard preprocessing sequence involves:
- Resizing: Images are resized to maintain aspect ratio while fitting within CLIP's input dimensions (typically 224×224 for ViT-based models). Center cropping is applied when the aspect ratio differs significantly.
- Normalization: Pixel values are scaled to [0,1] range then normalized using ImageNet statistics:
$$ \text{normalized} = \frac{\text{input} - [0.48145466, 0.4578275, 0.40821073]}{[0.26862954, 0.26130258, 0.27577711]} $$
- Channel ordering: Conversion to CHW format (Channels × Height × Width) for PyTorch compatibility.
Text Preprocessing Requirements
Text inputs require tokenization using CLIP's specific vocabulary (49408 tokens) with these key considerations:
- Context length: Maximum of 77 tokens including start/end markers
- Prompt engineering: Wrapping class labels in descriptive templates (e.g., "a photo of a {label}") improves zero-shot performance by better matching CLIP's training distribution
- Case handling: The tokenizer is case-sensitive, requiring consistent lowercase conversion when appropriate
Batch Processing Optimization
For efficient GPU utilization during inference:
Where model footprint includes both the encoded images (N×D) and text embeddings (C×D) for N images and C classes. Mixed-precision (FP16) inference typically reduces memory requirements by 40% without accuracy loss.
Data Augmentation Strategies
While zero-shot classification doesn't require training, test-time augmentation can improve robustness:
- Multi-crop evaluation: Averaging predictions across multiple crops (typically 5-10) per image
- Geometric transforms: Limited rotation (±15°) and horizontal flipping when orientation invariance is desired
- Color jitter: Minor adjustments (±0.1) to brightness, contrast, and saturation for illumination invariance
# Example CLIP preprocessing pipeline
from torchvision import transforms
clip_preprocess = transforms.Compose([
transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.48145466, 0.4578275, 0.40821073],
std=[0.26862954, 0.26130258, 0.27577711]
)
])
4.3 Defining Custom Prompts
Custom prompt engineering is critical for optimizing CLIP's zero-shot classification performance. Unlike traditional classifiers, CLIP leverages natural language prompts to condition its vision-language embeddings, making prompt design a hyperparameter that directly impacts model behavior. The key challenge lies in crafting prompts that maximize semantic alignment between text and image embeddings while minimizing bias.
Prompt Template Formulation
CLIP's text encoder processes prompts as raw strings, typically following the pattern "a photo of a {class}". However, this baseline template can be refined through:
- Class-specific context: Adding domain-relevant descriptors (e.g., "a satellite photo of a {class}" for remote sensing)
- Style variations: Testing pluralization ("photos of {class}") or articles ("an image showing the {class}")
- Multimodal cues: Incorporating attributes like "a grayscale microscope image of {class}"
Ensemble Prompting Strategies
Single-prompt approaches risk undersampling the latent semantic space. Ensemble methods improve robustness by:
- Prompt averaging: Computing mean embeddings across multiple templates
- Domain-adaptive sampling: Generating prompts via LLMs conditioned on task metadata
- Contrastive augmentation: Including negative prompts (e.g., "not a {class}") to sharpen decision boundaries
Hyperparameter Optimization
Prompt engineering interacts with CLIP's temperature parameter τ, which scales logits before softmax:
Optimal τ varies by prompt set and typically requires grid search over [0.01, 10.0]. Ablation studies show that prompt diversity reduces τ sensitivity by 42% compared to single-prompt baselines.
Bias Mitigation Techniques
Prompt engineering must counteract dataset biases amplified by CLIP's pretraining:
- Debiasing prefixes: Prepending "a balanced dataset photo of" to prompts
- Adversarial filtering: Removing prompts that maximize disparity between protected classes
- Concept activation vectors: Projecting prompts to orthogonalize sensitive attributes
import clip
import torch
model, preprocess = clip.load("ViT-B/32")
class_names = ["cat", "dog", "bird"]
prompts = [f"a high-resolution photo of a {label}" for label in class_names]
text_inputs = torch.cat([clip.tokenize(p) for p in prompts])
with torch.no_grad():
text_features = model.encode_text(text_inputs).float()
text_features /= text_features.norm(dim=-1, keepdim=True)
4.4 Running Zero-Shot Predictions
Zero-shot classification with CLIP leverages its joint embedding space to compute similarity scores between image and text features without task-specific fine-tuning. Given an input image x and a set of candidate class labels {y1, y2, ..., yk}, CLIP computes the probability distribution over classes as follows:
where fimage and ftext are CLIP's vision and text encoders, sim is cosine similarity, and τ is a temperature parameter learned during training. The key steps for implementation are:
Feature Extraction
First, encode the input image and candidate class labels into their respective embedding spaces:
import clip
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
# Preprocess image and tokenize text
image_input = preprocess(image).unsqueeze(0).to(device)
text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}") for c in class_labels]).to(device)
Similarity Computation
Compute logits by projecting image and text features into a shared space and measuring their cosine similarity:
with torch.no_grad():
image_features = model.encode_image(image_input)
text_features = model.encode_text(text_inputs)
# L2-normalize features and compute similarity
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)
logits = (image_features @ text_features.T) * model.logit_scale.exp()
Probability Calibration
Convert logits to probabilities via softmax with temperature scaling:
where I and T are normalized image and text embeddings. The temperature parameter τ controls the sharpness of the probability distribution.
Practical Considerations
- Prompt Engineering: Wrapping class labels in templates like "a photo of a {label}" improves alignment with CLIP's pretraining distribution.
- Batch Processing: For multi-image evaluation, compute text features once and reuse them across image batches.
- Domain Shift: Performance degrades when test data distribution differs significantly from CLIP's training data (WebImageText).
For multi-modal retrieval tasks, the same architecture can rank images against arbitrary textual queries by sorting based on similarity scores, enabling applications like content-based image search without labeled data.

4.5 Evaluating Model Performance
Evaluating zero-shot classification models like CLIP requires specialized metrics that account for the model's ability to generalize to unseen classes without fine-tuning. Unlike traditional supervised learning, where accuracy is computed against a fixed label set, zero-shot evaluation measures how well the model aligns text and image embeddings across diverse, potentially novel categories.
Key Evaluation Metrics
The primary metrics for assessing CLIP's zero-shot performance include:
- Top-1 Accuracy: The percentage of test samples where the highest-probability predicted class matches the true label.
- Top-5 Accuracy: The percentage of test samples where the true label appears in the top five predicted classes.
- Mean Class Accuracy: The average per-class accuracy, mitigating bias from imbalanced datasets.
- Cosine Similarity: Measures the alignment between image and text embeddings, with higher values indicating better semantic matching.
Mathematical Formulation
Given an image embedding v and a set of text embeddings {t1, t2, ..., tk} for k classes, the zero-shot classification probability for class i is computed as:
where τ is a temperature parameter learned during CLIP's contrastive pre-training. The cosine similarity cos(v, ti) is defined as:
Dataset Considerations
Standard benchmarks for evaluating CLIP include:
- ImageNet: Measures generalization across 1,000 classes, with variants like ImageNet-V2 for out-of-distribution testing.
- CIFAR-10/100: Evaluates performance on smaller, more focused datasets.
- Domain-Specific Datasets: Such as EuroSAT for satellite imagery or Describable Textures (DTD) for material classification.
For robust evaluation, datasets should include:
- Diverse visual concepts to test generalization.
- Multiple text prompts per class to assess sensitivity to phrasing.
- Out-of-distribution samples to evaluate zero-shot transfer.
Practical Implementation
To compute zero-shot accuracy programmatically:
import torch
from clip import clip
def evaluate_zero_shot(model, preprocess, dataset, class_descriptions):
model.eval()
correct = 0
total = 0
# Encode all text descriptions
text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}") for c in class_descriptions])
text_features = model.encode_text(text_inputs)
text_features /= text_features.norm(dim=-1, keepdim=True)
for image, label in dataset:
# Preprocess and encode image
image_input = preprocess(image).unsqueeze(0)
image_features = model.encode_image(image_input)
image_features /= image_features.norm(dim=-1, keepdim=True)
# Compute similarity and predict
similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
predicted = similarity.argmax()
correct += (predicted == label).sum().item()
total += 1
return correct / total
Advanced Evaluation Techniques
For research-grade evaluation, consider:
- Prompt Ensembling: Average predictions across multiple text prompts (e.g., "a photo of a {class}", "a cropped image of a {class}") to reduce variance.
- Calibration: Adjust the temperature parameter τ on a validation set to optimize confidence calibration.
- Cross-Modal Retrieval: Evaluate bidirectional performance (image-to-text and text-to-image retrieval) using metrics like Recall@K.
When comparing CLIP to other models, ensure:
- Identical evaluation protocols (same prompts, dataset splits).
- Hardware consistency (e.g., FP16 vs. FP32 inference).
- Reporting of both per-class and aggregate metrics.
5. Fine-Tuning CLIP for Domain-Specific Tasks
5.1 Fine-Tuning CLIP for Domain-Specific Tasks
While CLIP's zero-shot capabilities are impressive, its performance can be further enhanced for specialized domains through fine-tuning. The pre-trained CLIP model learns a joint embedding space for images and text, but this space may not optimally align with niche datasets where semantic relationships differ from general web-scale data. Fine-tuning adapts CLIP's vision and text encoders to better capture domain-specific features.
Contrastive Loss Adaptation
The core training objective remains contrastive learning, but with modified temperature scaling and hard negative mining to handle domain shifts. The loss function for a batch of N image-text pairs is:
where \( s_{ij} \) is the cosine similarity between the i-th image and j-th text embedding, and \( \tau \) is the learned temperature parameter. Domain adaptation introduces two key modifications:
- Dynamic Temperature: Replace the fixed \( \tau \) with a learned parameter \( \tau_d \) that adjusts based on the batch's hardness:
- Hard Negative Mining: Upweight samples where \( s_{ij}_{i \neq j} > \alpha \cdot s_{ii} \) by a factor \( \beta \) in the loss computation.
Architectural Modifications
For specialized domains, consider these architectural adjustments:
- Projection Head Expansion: Add a domain-specific projection head parallel to CLIP's existing projection layer. The final embedding becomes:
where \( \lambda \) is a learned mixing parameter initialized at 0.9.
- Prompt Engineering: Replace generic class names with domain-specific descriptors. For medical imaging, instead of "dog", use "canine thoracic radiograph showing cardiomegaly".
Training Protocol
The recommended fine-tuning procedure:
- Freeze the first 6 layers of both encoders, only tuning higher layers
- Use AdamW optimizer with cosine decay learning rate:
- Apply MixUp augmentation with \( \alpha=0.2 \) for image inputs
- Use gradient clipping at norm 1.0
For a batch size of 512, typical hyperparameters are \( \eta_{max}=5e-5 \), \( \eta_{min}=1e-6 \), trained for 5-20 epochs depending on dataset size.
Evaluation Metrics
Beyond standard accuracy, track these domain-specific metrics:
- Cross-modal Retrieval Precision@K: Percentage of top-K retrieved items that are relevant
- Embedding Cluster Purity: Measures separation between classes in the embedding space
- Domain Shift Score: \( \frac{||\mu_{src} - \mu_{tgt}||}{\sqrt{\sigma_{src}^2 + \sigma_{tgt}^2}} \) where \( \mu \) and \( \sigma \) are embedding distribution moments
Case Study: Medical Imaging
When fine-tuning CLIP for chest X-ray classification:
- Text prompts included radiology report snippets
- Added a DenseNet-121 parallel pathway for local lesion detection
- Achieved 92.3% accuracy on NIH ChestX-ray14, versus 78.1% in zero-shot mode
# Sample fine-tuning snippet
import torch
from clip.model import CLIP
model, preprocess = CLIP.from_pretrained('ViT-B/32')
for param in model.visual.transformer.resblocks[:6].parameters():
param.requires_grad = False
optimizer = torch.optim.AdamW(
filter(lambda p: p.requires_grad, model.parameters()),
lr=5e-5,
weight_decay=0.01
)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer, T_max=20, eta_min=1e-6
)

Combining CLIP with Other Models
CLIP's joint embedding space enables seamless integration with other deep learning models, unlocking novel architectures for multimodal tasks. The key lies in leveraging CLIP's pre-trained encoders to extract semantically aligned representations, which can then serve as inputs or conditioning signals for downstream models.
Architectural Fusion Strategies
Three primary approaches exist for combining CLIP with other models:
- Feature Concatenation: CLIP embeddings are concatenated with features from other modalities (e.g., audio spectrograms, LiDAR point clouds) before feeding into a fusion network.
- Cross-Attention: CLIP embeddings serve as keys/values in attention layers of transformer-based models, enabling dynamic information retrieval.
- Adapter Layers: Lightweight neural modules project CLIP outputs into the input space of frozen pretrained models.
where σ is a nonlinear activation, W are learned projection matrices, and b is a bias term.
Case Study: CLIP + Diffusion Models
Stable Diffusion demonstrates the power of combining CLIP with generative models. The text encoder processes prompts into embeddings that condition the diffusion process through cross-attention:
where Q comes from the U-Net's intermediate features and K,V are linear projections of CLIP embeddings.
Optimization Considerations
When fine-tuning combined systems:
- Gradient flow through CLIP's text encoder often requires careful learning rate scheduling (typically 10× lower than other components)
- Contrastive loss between modalities can stabilize training:
$$ \mathcal{L}_{contrast} = -\log\frac{\exp(\text{sim}(z_i,z_j)/\tau)}{\sum_k \exp(\text{sim}(z_i,z_k)/\tau)} $$
- Layer-wise adaptive rate decay preserves CLIP's pretrained knowledge while allowing feature adaptation
Real-World Implementation
The CLIPSeg architecture demonstrates practical integration by using CLIP's image encoder outputs as queries for a segmentation decoder:
import torch
from transformers import CLIPModel, CLIPProcessor
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
# Extract multimodal embeddings
inputs = processor(text=["a dog"], images=image, return_tensors="pt", padding=True)
outputs = clip_model(**inputs)
image_emb = outputs.image_embeds # [1, 512]
text_emb = outputs.text_embeds # [1, 512]
# Combine with downstream model
segmentation_input = torch.cat([image_emb, text_emb], dim=-1)
This approach achieves zero-shot segmentation by computing pixel-wise similarity between image features and text-derived prototypes.

5.3 Handling Bias and Improving Fairness
Sources of Bias in CLIP
CLIP, like other large-scale vision-language models, inherits biases from its training data, which consists of web-scale image-text pairs. These biases manifest in multiple forms:
- Representational Bias: Underrepresentation of certain demographic groups in training data leads to skewed performance across genders, ethnicities, or cultural contexts.
- Labeling Bias: Noisy or stereotypical text descriptions in the dataset reinforce harmful associations (e.g., gender-occupation correlations).
- Semantic Bias: The text encoder may associate certain words with negative or positive connotations based on co-occurrence patterns.
Quantifying Bias
To measure bias, we compute disparity metrics across protected attributes (e.g., race, gender) for a given classification task. For a set of images X and protected attribute A, the demographic parity difference (DPD) is:
where Ŷ is the model's prediction. A similar metric, equalized odds difference (EOD), evaluates:
Mitigation Strategies
Data-Centric Approaches
Curate balanced evaluation datasets with stratified sampling across protected attributes. For text prompts, use counterfactual augmentation:
- Replace gendered terms ("CEO" → "CEO, a woman" / "CEO, a man")
- Add demographic context to class descriptions
Model-Centric Approaches
Fine-tune CLIP with fairness constraints. The loss function L can be modified as:
where λ controls the fairness-accuracy trade-off. Alternatively, use adversarial debiasing by training a discriminator to predict protected attributes from embeddings, then minimizing its accuracy.
Architectural Interventions
Modify the attention mechanism in CLIP's text encoder to suppress biased token interactions. For a given attention head, compute the contribution C of biased terms:
then apply suppression masks to attention weights for sensitive tokens.
Evaluation Protocols
Standard benchmarks include:
- FairFace: Balanced facial dataset across race, gender, and age groups
- BiasBios: Profession classification with counterfactual augmentation
- Winoground: Tests for stereotypical visual-textual associations
Report metrics both overall and disaggregated by protected attributes. Statistical significance testing (e.g., McNemar's test) should accompany any claims of improved fairness.
6. Zero-Shot Classification in E-Commerce
6.1 Zero-Shot Classification in E-Commerce
Zero-shot classification with CLIP (Contrastive Language–Image Pretraining) leverages multimodal embeddings to classify images without task-specific training. In e-commerce, this enables dynamic product categorization, attribute tagging, and visual search without fine-tuning on labeled datasets. The core mechanism relies on aligning image and text embeddings in a shared latent space, allowing similarity-based classification.
Mathematical Foundation
Given an image x and a set of candidate class labels {y₁, y₂, ..., yₙ}, CLIP computes the probability P(yᵢ|x) via cosine similarity in the joint embedding space:
where EI and ET are the image and text encoders, cos denotes cosine similarity, and τ is a temperature parameter learned during pretraining. The text encoder processes class labels as natural language prompts (e.g., "a photo of a {class}").
E-Commerce Applications
- Product Categorization: Classify items into hierarchical taxonomies (e.g., "Electronics → Smartphones") using zero-shot prompts.
- Attribute Extraction: Infer material ("cotton"), style ("vintage"), or other attributes without manual annotation.
- Visual Search: Retrieve similar products by comparing image embeddings against a database.
Case Study: Dynamic Fashion Tagging
A fashion retailer uses CLIP to tag 10M product images with 500+ attributes (e.g., "striped", "formal"). The text encoder processes templates like "This clothing item is {attribute}", while the image encoder generates embeddings for similarity scoring. This achieves 85% precision on unseen attributes, outperforming supervised models trained on limited labeled data.
Optimization Strategies
For large-scale deployment:
- Prompt Engineering: Refine text templates (e.g., "a product photo of {label} for e-commerce") to align with domain-specific language.
- Embedding Caching: Precompute text embeddings for all candidate classes to reduce inference latency.
- Thresholding: Reject low-confidence predictions (cosine similarity < 0.3) to minimize misclassifications.
Limitations and Mitigations
CLIP's performance degrades for:
- Fine-Grained Classes: Distinguishing "iPhone 13" vs. "iPhone 14" requires domain adaptation via few-shot learning.
- Cultural Bias: Pretraining data skew may misclassify region-specific items (e.g., traditional attire). Mitigate by augmenting prompts with locale context.
import clip
import torch
from PIL import Image
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
# Zero-shot prediction
image = preprocess(Image.open("product.jpg")).unsqueeze(0).to(device)
text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}") for c in ["dress", "shirt", "pants"]]).to(device)
with torch.no_grad():
image_features = model.encode_image(image)
text_features = model.encode_text(text_inputs)
logits = (image_features @ text_features.T).softmax(dim=-1)

6.2 Medical Image Classification with CLIP
CLIP's zero-shot classification capabilities extend naturally to medical imaging, where labeled datasets are often scarce or expensive to curate. The model's ability to associate images with textual descriptions enables it to classify medical scans without task-specific fine-tuning. Given an input image I and a set of candidate class labels C = {c₁, c₂, ..., cₙ}, CLIP computes the probability distribution over classes by comparing the image embedding f(I) with text embeddings g(cᵢ) of prompt-engineered class descriptions.
Prompt Engineering for Medical Domains
Medical classification requires careful prompt design to align CLIP's latent space with clinical terminology. For a chest X-ray classification task distinguishing between "normal", "pneumonia", and "tuberculosis", effective prompts might include:
- "A frontal chest radiograph showing normal lung anatomy"
- "An X-ray demonstrating lung consolidations consistent with pneumonia"
- "A chest film revealing apical opacities suggestive of tuberculosis"
The similarity score between image and text embeddings is computed using the cosine similarity:
Domain-Specific Adaptation
While CLIP performs reasonably on medical images out-of-the-box, several adaptations improve performance:
- Contrastive Fine-Tuning: Train CLIP on paired medical images and radiology reports to better align the embedding spaces
- Ensemble Prompting: Combine multiple prompt variations (e.g., "a CT scan showing [class]" and "an axial view of [class]") and average their similarity scores
- Anatomical Masking: Apply segmentation masks to focus embeddings on relevant regions (e.g., lung fields in chest X-rays)
Performance Metrics
On the CheXpert dataset (224×224 chest X-rays), zero-shot CLIP achieves:
When augmented with anatomical masking and ensemble prompting, performance improves to:
Implementation Example
The following Python code demonstrates zero-shot classification of chest X-rays using CLIP:
import clip
import torch
from PIL import Image
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
classes = ["normal", "pneumonia", "tuberculosis"]
prompts = [f"A chest X-ray showing {c}" for c in classes]
image = preprocess(Image.open("chest_xray.png")).unsqueeze(0).to(device)
text = clip.tokenize(prompts).to(device)
with torch.no_grad():
image_features = model.encode_image(image)
text_features = model.encode_text(text)
logits = (image_features @ text_features.T).softmax(dim=-1)
predicted_class = classes[logits.argmax().item()]
6.3 Content Moderation Applications
Zero-shot classification with CLIP offers a powerful approach to content moderation by leveraging its ability to classify images and text without task-specific training. Traditional moderation systems rely on supervised models trained on labeled datasets, which struggle with novel or evolving harmful content. CLIP's zero-shot capability allows it to generalize across unseen categories, making it particularly effective for dynamic moderation tasks.
Moderation as a Zero-Shot Classification Task
Content moderation can be framed as a binary or multi-class classification problem where inputs are scored against predefined categories such as violence, hate speech, or explicit content. Given a set of candidate labels $$ L = \{l_1, l_2, \dots, l_k\} $$, CLIP computes the similarity between an input (image or text) and each label in the joint embedding space. The probability that an input $$ x $$ belongs to class $$ l_i $$ is given by:
where $$ f $$ and $$ g $$ are the image and text encoders, $$ \text{sim} $$ is cosine similarity, and $$ \tau $$ is a temperature parameter.
Handling Contextual Nuance
Unlike keyword-based filters, CLIP captures semantic context, reducing false positives. For example, an image of a medical diagram might contain nudity but is not explicit. By encoding both the image and descriptive labels (medical illustration vs. explicit content), CLIP can disambiguate intent. Similarly, text snippets containing slurs can be classified as hate speech only if their contextual similarity to harmful intent exceeds a threshold.
Dynamic Policy Adaptation
Platforms frequently update moderation policies to address emerging threats. With CLIP, new rules can be implemented by simply adding or modifying label descriptions without retraining. For instance, during a crisis involving self-harm trends, a platform can immediately introduce labels like self-harm encouragement and compute their similarity scores against user-generated content.
Multimodal Moderation
CLIP's ability to process both text and images enables cross-modal verification. A post containing an image with violent imagery and a benign caption can be flagged if either modality scores highly against harmful categories. The combined score can be computed as:
where $$ \alpha $$ is a weighting factor tuned for precision-recall trade-offs.
Limitations and Mitigations
While CLIP reduces reliance on labeled data, its performance depends on the phrasing of candidate labels. Adversarial attacks, such as misspelled hate speech or cropped explicit images, can bypass detection. Hybrid approaches—combining CLIP with rule-based filters or fine-tuned detectors—improve robustness. Additionally, threshold tuning via ROC analysis ensures optimal precision for high-stakes decisions.
7. Key Research Papers on CLIP
7.1 Key Research Papers on CLIP
- How to use CLIP Zero-Shot on your own classificaiton dataset — This notebook provides an example of how to benchmark CLIP's zero shot classification performance on your own classification dataset. CLIP is a new zero shot image classifier relased by OpenAI that has been trained on 400 million text/image pairs across the web. CLIP uses these learnings to make predicts based on a flexible span of possible classification categories.
- PDF CLIP-KD: An Empirical Study of CLIP Model Distillation - CVF Open Access — proves student CLIP models consistently over zero-shot ImageNet classification and cross-modal retrieval bench-marks. When using ViT-L/14 pretrained on Laion-400M as the teacher, CLIP-KD achieves 57.5% and 55.4% zero-shot top-1 ImageNet accuracy over ViT-B/16 and ResNet-50, surpassing the original CLIP without KD by 20.5%
- PDF D CLIP LATENTS FOR ZERO-SHOT APTIONING VIA TEXT-ONLY TRAINING - OpenReview — Published as a conference paper at ICLR 2023 DECAP: DECODING CLIP LATENTS FOR ZERO-SHOT CAPTIONING VIA TEXT-ONLY TRAINING Wei Li 1Linchao Zhu Longyin Wen2 Yi Yang ∗ 1CCAI, Zhejiang University 2ByteDance Inc., San Jose, USA {weili6,zhulinchao,yangyics}@zju.edu.cn [email protected] ABSTRACT Large-scale pre-trained multi-modal models (e.g., CLIP) demonstrate strong zero-
- MjdMahasneh/zero-shot-CLIP-based-image-classification — CLIP (Contrastive Language-Image Pretraining) enables zero-shot image classification by associating images with text descriptions. Here's how it works: Pre-trained Model: CLIP is trained on a large dataset of image-text pairs.; Text Prompts: For classification, text descriptions of classes (e.g., "a photo of a cat," "a photo of a dog") are used as prompts.
- Exploring CLIP - 2023W, UCLA CS188 Course Projects — This is the plot illustrating their finding, obtained from CLIP's original paper. 1. Fig 4. Few-shot underperform zero-shot 1. Method. Our method comes from the idea that the zero-shot classifier itself is just a linear classifier on the features of CLIP, so we may initialize our linear classifier to match the zero-shot classifier.
- Application of CLIP for efficient zero-shot learning — 2.1 Zero-shot learning. Research in ZSL aims to transfer knowledge from seen to unseen classes using auxiliary semantic priors. Key explorations in this domain have involved diverse semantic priors, such as user-defined attributes [], word vectors [], and textual descriptions [].In order to expand semantic priors, innovative approaches leaverage latent semantic space [7, 8, 18, 19].
- TLAC: Two-stage LMM Augmented CLIP for Zero-Shot Classification — Contrastive Language-Image Pretraining (CLIP) has shown impressive zero-shot performance on image classification. However, state-of-the-art methods often rely on fine-tuning techniques like prompt ...
- Single-stage zero-shot object detection network based on CLIP and ... — Single-stage zero-shot object detection framework. In the training phase, the CLIP text embedding of the base category \(c_b\) is used for initialization, the typical category output is replaced by a semantic output equal to the size of the CLIP model embedding, and the features of the sparse positive sample points on the feature map are minimized by formulating \({\mathcal {L}}_{img ...
- PDF The Unreasonable Effectiveness of CLIP Features for Image Captioning ... — domain performance, and zero-shot performance, and that are largely superior to features used in previous lines of research. Indeed, a simple Transformer-based captioner, equipped with CLIP features, can largely overcome state of the art approaches based on significantly more complex ar-chitectures. This effectiveness is quantified both as a func-
- PDF AdaCLIP: Adapting CLIP with Hybrid Learnable Prompts for Zero-Shot ... — AdaCLIP 5 * indicatingwhether (static+dynamic)promptstoadaptVLMsforimprovinganomalydetection.
7.2 Tutorials and Implementation Guides
- Reaching 80% zero-shot accuracy with OpenCLIP: ViT-G/14 trained ... - LAION — We have trained a new ViT-G/14 CLIP model with OpenCLIP which achieves 80.1% zero-shot accuracy on ImageNet and 74.9% zero-shot image retrieval (Recall@5) on MS COCO. As of January 2023, this is the best open source CLIP model. We believe this is interesting because: CLIP models are useful for zero-shot classification, retrieval, and for guidance/conditioning in generative models (OpenCLIP is ...
- PDF Label Propagation for Zero-shot Classification with Vision-Language ... — tive and inductive zero-shot classification results on Ima-geNet with additional CLIP backbones. We present results with two versions of ViT-L-14 from CLIP [4]. Additionally, we present the results with ViT-B-16 and ViT-H-14 from OpenCLIP [1]1 trained on the LAION-2B [5] dataset. We see from Table2that ZLaP improves the results with dif-
- PDF Transductive Zero-Shot and Few-Shot CLIP - CVF Open Access — of our mini-batch inference approach. On zero-shot Im-ageNet tasks with batches of 75 samples, the proposed method scores near 20% higher than inductive zero-shot CLIP in classification accuracy. Additionally, we out-perform state-of-the-art methods in the few-shot setting. 2. Related works 2.1. Vision-language models
- Making Better Mistakes in CLIP-Based Zero-Shot Classification — 1 Introduction Figure 1: Overall process of the proposed CLIP-based zero-shot classification. We introduce prior knowledge of the label hierarchy to the language prompts used to query the LLM. Figure 2: Histogram of mistake severities for predictions of CLIP (zero-shot) and ViTs (trained with ImageNet from scratch) on ImageNet. The mistake severities of predictions are derived from our label ...
- How to use CLIP Zero-Shot on your own classificaiton dataset — This notebook provides an example of how to benchmark CLIP's zero shot classification performance on your own classification dataset. CLIP is a new zero shot image classifier relased by OpenAI that has been trained on 400 million text/image pairs across the web. CLIP uses these learnings to make predicts based on a flexible span of possible classification categories.
- Improving Zero-Shot Generalization for CLIP with Variational Adapter — 2.1 Generalized Zero-Shot Learning. How to recognize objects in an open-world visual environment has attracted increasing interest in recent years. GZSL [5, 22, 23, 39] is one of the relevant research fields focusing on open-world visual tasks.Specifically, GZSL aims to recognize both base and novel objects, relying solely on labeled samples from the base classes.
- PDF Robust Fine-Tuning of Zero-Shot Models - CVF Open Access — zero-shot= (1 ) zero-shot + ne-tuned ne-tuned Schematic: our method, WiSE-FT leads to better accuracy on the distribution shifts without decreasing accuracy on the reference distribution V aryingam ixingaco ef fi c i e n t a 55 60 65 70 75 80 85 ImageNet (top-1, %) 30 35 40 45 50 55 60 65 70 75 Avg. accuracy on 5 distribution shifts Real data ...
- ZegCLIP/README.md at main · ZiqinZhou66/ZegCLIP · GitHub — The general idea is to first generate class-agnostic region proposals and then feed the cropped proposal regions to CLIP to utilize its image-level zero-shot classification capability. While effective, such a scheme requires two image encoders, one for proposal generation and one for CLIP, leading to a complicated pipeline and high ...
- PDF Improving Zero-Shot Generalization for CLIP with Variational Adapter — Keywords: Visual-LanguageModels· Zero-ShotGeneralization· Vari-ationalAdapter 1 Introduction Recently, pre-trained Vision-Language Models (VLMs) such as CLIP [31] and ALIGN [18] have demonstrated remarkable applicability across various down-stream tasks such as Zero-Shot Learning (ZSL) [1,38]. To further boost the
- PDF Zero/Few-Shot Text Classification - DiVA — Zero/Few-ShotText Classification AStudyofPracticalAspectsand Applications JacobÅslund Master'sProgramme,MachineLearning,120credits Date:August19,2021
7.3 Ethical Considerations and Best Practices
- PDF WinCLIP: Zero-/Few-Shot Anomaly Classification and Segmentation — improves zero-shot anomaly classification over the na¨ıve CLIP based zero-shot classification. • Using the pre-trained CLIP model, we propose Win-CLIP, that efficiently extract and aggregate multi-scale spatial features aligned with language for zero-shot anomaly segmentation. As far as we know, we are the first to explore language-guided ...
- GitHub - cs582/CLIP_implementation: From scratch implementation of ... — CLIP is an AI tool developed by OpenAI that connects images to text with zero-shot capabilities similar to those of GPT-2 and GPT-3. It uses Natural Language Processing for zero-shot classification. This project implements the ground-breaking paper by OpenAI on test-image connection and zero-shot classification: CLIP.
- Semantic matters: A constrained approach for zero-shot video action ... — Beyond extensive research in zero-shot image classification, zero-shot video action recognition has also ... Zero-shot setting: The SC-CLIP approach begins with training on the K-400 dataset and is then assessed on the UCF-101, HMDB-51, and K-600 datasets. For the UCF-101 and HMDB-51 datasets, we employ the three test splits from the official ...
- How to use CLIP Zero-Shot on your own classificaiton dataset — This notebook provides an example of how to benchmark CLIP's zero shot classification performance on your own classification dataset. CLIP is a new zero shot image classifier relased by OpenAI that has been trained on 400 million text/image pairs across the web. CLIP uses these learnings to make predicts based on a flexible span of possible classification categories.
- Making Better Mistakes in CLIP-Based Zero-Shot Classification — 1 Introduction Figure 1: Overall process of the proposed CLIP-based zero-shot classification. We introduce prior knowledge of the label hierarchy to the language prompts used to query the LLM. Figure 2: Histogram of mistake severities for predictions of CLIP (zero-shot) and ViTs (trained with ImageNet from scratch) on ImageNet. The mistake severities of predictions are derived from our label ...
- PDF Zero-Shot Learning - the Good, the Bad and the Ugly - CVF Open Access — but also in the more realistic generalized zero-shot setting. Finally, we discuss limitations of the current status of the area which can be taken as a basis for advancing it. 1. Introduction Zero-shot learning aims to recognize objects whose in-stances may not have been seen during training [17, 22, 23, 30, 40]. The number of new zero-shot ...
- PDF Preventing Zero-Shot Transfer Degradation in Continual Learning of ... — ful zero-shot transfer ability [44,23,32]. They can give zero-shot predictions without any training examples of a task. However, the performance on some tasks is poor due to insufficient relevant image-text pairs in the pre-training datasets. For example, it is difficult for CLIP [44] to distinguish among digital numbers, with an accuracy on
- arXiv:2404.04072v1 [cs.CV] 5 Apr 2024 — performs zero-shot classification using sub-classes and link-ing them to the parent class. We show that methods improv-ing the textual prompts are complementary to our approach. Synthetic data. Recent methods [9,38,43] demonstrate that the use of synthetic data is beneficial for zero-shot classification. CLIP+SYN [9] uses a stable-diffusion-based
- Relation-based Discriminative Cooperation Network for Zero-Shot ... — On AWA2 dataset, RDCN gets a best accuracy of 56.6% on the first setting ("ts" value) and 63.5% overall. ... benchmarks with multiple settings including both ZSL and GZSL demonstrated the superiority of the proposed model for zero-shot classification. In the future, since the acquisition of attributes requires prior knowledge, we plan to ...
- Artificial intelligence foundation and pre-trained ... - ScienceDirect — CLIP was trained on 400 million image-caption pairs, learning to link semantic similarity between text and pictures [14]. This type of pre-training approach turned out to create strong picture and text features, which may be used for a number of downstream tasks such as search and zero shot classification [14].








