Zero-Shot Image Classification
Transformers
Safetensors
English
clip
fashion
multimodal
image-search
text-search
embeddings
contrastive-learning
zero-shot-classification
Run this model with HF Jobs
Run Leacb4/gap-clip on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Leacb4/gap-clip. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Leacb4/gap-clip on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Leacb4/gap-clip with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Leacb4/gap-clip with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("zero-shot-image-classification", model="Leacb4/gap-clip") pipe( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png", candidate_labels=["animals", "humans", "landscape"], )# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForZeroShotImageClassification processor = AutoProcessor.from_pretrained("Leacb4/gap-clip") model = AutoModelForZeroShotImageClassification.from_pretrained("Leacb4/gap-clip", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload evaluation/main_model_evaluation.py with huggingface_hub
Browse files18 unmodified lines19202122232425150 unmodified lines176177178179180181182417 unmodified lines60060160260360460560660760860961061161261313 unmodified lines62762862963063163263363463534 unmodified lines6706716726736746756766775 unmodified lines683684685686687688194 unmodified lines8838848858868878889 unmodified lines898899900901902903904905906907908137 unmodified lines10461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113610 unmodified lines172417251726172717281729173048 unmodified lines177917801781178217831784178543 unmodified lines182918301831183218331834183518 unmodified lineswarnings.filterwarnings('ignore')from transformers import CLIPProcessor, CLIPModel as CLIPModel_transformersfrom config import main_model_path, hierarchy_model_path, color_emb_dim, hierarchy_emb_dim, local_dataset_path, column_local_image_path, fashion_mnist_test_pathdef create_fashion_mnist_to_hierarchy_mapping(hierarchy_classes):150 unmodified linesdef load_fashion_mnist_dataset(max_samples=1000, hierarchy_classes=None):print("📊 Loading Fashion-MNIST test dataset...")df = pd.read_csv(fashion_mnist_test_path)print(f"✅ Fashion-MNIST dataset loaded: {len(df)} samples")# Create mapping if hierarchy classes are provided417 unmodified linesreturn sorted(set(hierarchies))def extract_color_embeddings(self, dataloader, embedding_type='text', max_samples=10000):"""Extract color embeddings from dims 0-16"""all_embeddings = []all_colors = []all_hierarchies = []sample_count = 0with torch.no_grad():for batch in tqdm(dataloader, desc=f"Extracting {embedding_type} color embeddings (dims 0-16)"):if sample_count >= max_samples:break13 unmodified lineselse:embeddings = outputs.text_embeds# Extract only color embeddings (dims 0-16)color_embeddings = embeddings[:, :self.color_emb_dim]all_embeddings.append(color_embeddings.cpu().numpy())all_colors.extend(colors)all_hierarchies.extend(hierarchies)34 unmodified linesembeddings = outputs.text_embeds# Extract hierarchy embeddings (dims 17-79 -> indices 16:79)hierarchy_embeddings = embeddings[:, 16:79]all_embeddings.append(hierarchy_embeddings.cpu().numpy())all_colors.extend(colors)all_hierarchies.extend(hierarchies)5 unmodified linesreturn np.vstack(all_embeddings), all_colors, all_hierarchiesdef extract_baseline_embeddings_batch(self, dataloader, embedding_type='text', max_samples=10000):"""Extract embeddings from baseline Fashion CLIP model"""all_embeddings = []194 unmodified linespredictions.append(predicted_label)return predictionsdef create_confusion_matrix(self, true_labels, predicted_labels, title="Confusion Matrix", label_type="Label"):"""Create and plot confusion matrix"""unique_labels = sorted(list(set(true_labels + predicted_labels)))9 unmodified linesplt.tight_layout()return plt.gcf(), accuracy, cmdef evaluate_classification_performance(self, embeddings, labels, embedding_type="Embeddings", label_type="Label"):"""Evaluate classification performance and create confusion matrix"""predictions = self.predict_labels_from_embeddings(embeddings, labels)accuracy = accuracy_score(labels, predictions)fig, acc, cm = self.create_confusion_matrix(labels, predictions, f"{embedding_type} - {label_type} Classification", label_type)unique_labels = sorted(list(set(labels)))report = classification_report(labels, predictions, labels=unique_labels, target_names=unique_labels, output_dict=True)return {137 unmodified linesresults = {}# ========== COLOR EVALUATION (DIMS 0-16) ==========print("\n🎨 COLOR EVALUATION (dims 0-16)")print("=" * 50)# Text color embeddingsprint("\n📝 Extracting text color embeddings...")text_color_embeddings, text_colors, _ = self.extract_color_embeddings(dataloader, 'text', max_samples)print(f" Text color embeddings shape: {text_color_embeddings.shape}")text_color_metrics = self.compute_similarity_metrics(text_color_embeddings, text_colors)text_color_class = self.evaluate_classification_performance(text_color_embeddings, text_colors, "Text Color Embeddings (16D)", "Color")text_color_metrics.update(text_color_class)results['text_color'] = text_color_metricsdel text_color_embeddingstorch.cuda.empty_cache() if torch.cuda.is_available() else None# Image color embeddingsprint("\n🖼️ Extracting image color embeddings...")image_color_embeddings, image_colors, _ = self.extract_color_embeddings(dataloader, 'image', max_samples)print(f" Image color embeddings shape: {image_color_embeddings.shape}")image_color_metrics = self.compute_similarity_metrics(image_color_embeddings, image_colors)image_color_class = self.evaluate_classification_performance(image_color_embeddings, image_colors, "Image Color Embeddings (16D)", "Color")image_color_metrics.update(image_color_class)results['image_color'] = image_color_metricsdel image_color_embeddingstorch.cuda.empty_cache() if torch.cuda.is_available() else None# ========== HIERARCHY EVALUATION (DIMS 16-79) ==========print("\n📋 HIERARCHY EVALUATION (dims 16-79)")print("=" * 50)# Text hierarchy embeddingsprint("\n📝 Extracting text hierarchy embeddings...")text_hierarchy_embeddings, _, text_hierarchies = self.extract_hierarchy_embeddings(dataloader, 'text', max_samples)print(f" Text hierarchy embeddings shape: {text_hierarchy_embeddings.shape}")text_hierarchy_metrics = self.compute_similarity_metrics(text_hierarchy_embeddings, text_hierarchies)text_hierarchy_class = self.evaluate_classification_performance(text_hierarchy_embeddings, text_hierarchies, "Text Hierarchy Embeddings (64D)", "Hierarchy")text_hierarchy_metrics.update(text_hierarchy_class)results['text_hierarchy'] = text_hierarchy_metricsdel text_hierarchy_embeddingstorch.cuda.empty_cache() if torch.cuda.is_available() else None# Image hierarchy embeddingsprint("\n🖼️ Extracting image hierarchy embeddings...")image_hierarchy_embeddings, _, image_hierarchies = self.extract_hierarchy_embeddings(dataloader, 'image', max_samples)print(f" Image hierarchy embeddings shape: {image_hierarchy_embeddings.shape}")image_hierarchy_metrics = self.compute_similarity_metrics(image_hierarchy_embeddings, image_hierarchies)image_hierarchy_class = self.evaluate_classification_performance(image_hierarchy_embeddings, image_hierarchies, "Image Hierarchy Embeddings (64D)", "Hierarchy")image_hierarchy_metrics.update(image_hierarchy_class)results['image_hierarchy'] = image_hierarchy_metricsdel image_hierarchy_embeddingstorch.cuda.empty_cache() if torch.cuda.is_available() else None# ========== SAVE VISUALIZATIONS ==========610 unmodified lines'trained': trained_color_img_acc,'baseline': baseline_color_img_acc,'diff': diff,'trained_dims': '0-16 (17 dims)','baseline_dims': 'All dimensions (512 dims)'})48 unmodified linesprint("\nRaisons probables:")print("\n1. 📐 CAPACITÉ DIMENSIONNELLE:")print(" • Baseline: Utilise TOUTES les 512 dimensions des embeddings")print(" • Modèle entraîné: Utilise seulement 17 dims (couleur) ou 64 dims (hiérarchie)")print(" • Impact: La baseline a accès à plus d'information pour la classification")print("\n2. 🎯 SUR-SPÉCIALISATION:")43 unmodified linesdevice = torch.device("mps" if torch.backends.mps.is_available() else "cpu")print(f"Using device: {device}")directory = 'main_model_analysi'max_samples = 10000evaluator = ColorHierarchyEvaluator(device=device, directory=directory)18 unmodified lines19202122232425150 unmodified lines176177178179180181182417 unmodified lines60060160260360460560660760860961061161261313 unmodified lines62762862963063163263363463563634 unmodified lines6716726736746756766776786795 unmodified lines685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730194 unmodified lines9259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769 unmodified lines98698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019137 unmodified lines1157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235610 unmodified lines184618471848184918501851185248 unmodified lines190119021903190419051906190743 unmodified lines195119521953195419551956195718 unmodified lineswarnings.filterwarnings('ignore')from transformers import CLIPProcessor, CLIPModel as CLIPModel_transformersfrom config import main_model_path, hierarchy_model_path, color_emb_dim, hierarchy_emb_dim, local_dataset_path, column_local_image_pathdef create_fashion_mnist_to_hierarchy_mapping(hierarchy_classes):150 unmodified linesdef load_fashion_mnist_dataset(max_samples=1000, hierarchy_classes=None):print("📊 Loading Fashion-MNIST test dataset...")df = pd.read_csv("/Users/leaattiasarfati/Desktop/docs/search/old/MainModel/data/fashion-mnist_test.csv")print(f"✅ Fashion-MNIST dataset loaded: {len(df)} samples")# Create mapping if hierarchy classes are provided417 unmodified linesreturn sorted(set(hierarchies))def extract_color_embeddings(self, dataloader, embedding_type='text', max_samples=10000):"""Extract color embeddings from dims 0-15 (16 dimensions)"""all_embeddings = []all_colors = []all_hierarchies = []sample_count = 0with torch.no_grad():for batch in tqdm(dataloader, desc=f"Extracting {embedding_type} color embeddings (dims 0-15)"):if sample_count >= max_samples:break13 unmodified lineselse:embeddings = outputs.text_embeds# Extract only color embeddings (dims 0-15, i.e., first 16 dimensions)# color_embeddings = embeddings[:, :self.color_emb_dim]color_embeddings = embeddingsall_embeddings.append(color_embeddings.cpu().numpy())all_colors.extend(colors)all_hierarchies.extend(hierarchies)34 unmodified linesembeddings = outputs.text_embeds# Extract hierarchy embeddings (dims 17-79 -> indices 16:79)# hierarchy_embeddings = embeddings[:, 16:79]hierarchy_embeddings = embeddingsall_embeddings.append(hierarchy_embeddings.cpu().numpy())all_colors.extend(colors)all_hierarchies.extend(hierarchies)5 unmodified linesreturn np.vstack(all_embeddings), all_colors, all_hierarchiesdef extract_full_embeddings(self, dataloader, embedding_type='text', max_samples=10000):"""Extract full 512-dimensional embeddings (all dimensions)"""all_embeddings = []all_colors = []all_hierarchies = []sample_count = 0with torch.no_grad():for batch in tqdm(dataloader, desc=f"Extracting {embedding_type} FULL embeddings (all dims)"):if sample_count >= max_samples:breakimages, texts, colors, hierarchies = batchimages = images.to(self.device)images = images.expand(-1, 3, -1, -1)text_inputs = self.processor(text=texts, padding=True, return_tensors="pt")text_inputs = {k: v.to(self.device) for k, v in text_inputs.items()}outputs = self.model(**text_inputs, pixel_values=images)if embedding_type == 'text':embeddings = outputs.text_embedselif embedding_type == 'image':embeddings = outputs.image_embedselse:embeddings = outputs.text_embeds# Use all 512 dimensionsall_embeddings.append(embeddings.cpu().numpy())all_colors.extend(colors)all_hierarchies.extend(hierarchies)sample_count += len(images)del images, text_inputs, outputs, embeddingstorch.cuda.empty_cache() if torch.cuda.is_available() else Nonereturn np.vstack(all_embeddings), all_colors, all_hierarchiesdef extract_baseline_embeddings_batch(self, dataloader, embedding_type='text', max_samples=10000):"""Extract embeddings from baseline Fashion CLIP model"""all_embeddings = []194 unmodified linespredictions.append(predicted_label)return predictionsdef predict_labels_ensemble(self, specialized_embeddings, full_embeddings, labels,specialized_weight=0.5):"""Ensemble prediction combining specialized (16/64 dims) and full (512 dims) embeddings.Args:specialized_embeddings: Embeddings from specialized dimensions (e.g., dims 0-15 for color)full_embeddings: Full 512-dimensional embeddingslabels: True labels for computing centroidsspecialized_weight: Weight for specialized embeddings (0.0 = only full, 1.0 = only specialized)Returns:List of predicted labels using weighted ensemble"""unique_labels = list(set(labels))# Compute centroids for both specialized and full embeddingsspecialized_centroids = {}full_centroids = {}for label in unique_labels:label_indices = [i for i, l in enumerate(labels) if l == label]specialized_centroids[label] = np.mean(specialized_embeddings[label_indices], axis=0)full_centroids[label] = np.mean(full_embeddings[label_indices], axis=0)predictions = []for i in range(len(specialized_embeddings)):best_combined_score = -np.infpredicted_label = Nonefor label in unique_labels:# Compute similarity scores for both specialized and fullspec_sim = cosine_similarity([specialized_embeddings[i]], [specialized_centroids[label]])[0][0]full_sim = cosine_similarity([full_embeddings[i]], [full_centroids[label]])[0][0]# Weighted combinationcombined_score = specialized_weight * spec_sim + (1 - specialized_weight) * full_simif combined_score > best_combined_score:best_combined_score = combined_scorepredicted_label = labelpredictions.append(predicted_label)return predictionsdef create_confusion_matrix(self, true_labels, predicted_labels, title="Confusion Matrix", label_type="Label"):"""Create and plot confusion matrix"""unique_labels = sorted(list(set(true_labels + predicted_labels)))9 unmodified linesplt.tight_layout()return plt.gcf(), accuracy, cmdef evaluate_classification_performance(self, embeddings, labels, embedding_type="Embeddings", label_type="Label",full_embeddings=None, ensemble_weight=0.5):"""Evaluate classification performance and create confusion matrix.Args:embeddings: Specialized embeddings (e.g., dims 0-15 for color or dims 16-79 for hierarchy)labels: True labelsembedding_type: Type of embeddings for displaylabel_type: Type of labels (Color/Hierarchy)full_embeddings: Optional full 512-dim embeddings for ensemble (if None, uses only specialized)ensemble_weight: Weight for specialized embeddings in ensemble (0.0 = only full, 1.0 = only specialized)"""if full_embeddings is not None:# Use ensemble predictionpredictions = self.predict_labels_ensemble(embeddings, full_embeddings, labels, ensemble_weight)title_suffix = f" (Ensemble: {ensemble_weight:.1f} specialized + {1-ensemble_weight:.1f} full)"else:# Use only specialized embeddingspredictions = self.predict_labels_from_embeddings(embeddings, labels)title_suffix = ""accuracy = accuracy_score(labels, predictions)fig, acc, cm = self.create_confusion_matrix(labels, predictions,f"{embedding_type} - {label_type} Classification{title_suffix}",label_type)unique_labels = sorted(list(set(labels)))report = classification_report(labels, predictions, labels=unique_labels, target_names=unique_labels, output_dict=True)return {137 unmodified linesresults = {}# ========== EXTRACT FULL EMBEDDINGS FOR ENSEMBLE ==========print("\n📦 Extracting full 512-dimensional embeddings for ensemble...")text_full_embeddings, text_colors_full, text_hierarchies_full = self.extract_full_embeddings(dataloader, 'text', max_samples)image_full_embeddings, image_colors_full, image_hierarchies_full = self.extract_full_embeddings(dataloader, 'image', max_samples)print(f" Text full embeddings shape: {text_full_embeddings.shape}")print(f" Image full embeddings shape: {image_full_embeddings.shape}")# ========== COLOR EVALUATION (DIMS 0-15) WITH ENSEMBLE ==========print("\n🎨 COLOR EVALUATION (dims 0-15) - Using Ensemble")print("=" * 50)# Extract specialized color embeddings (dims 0-15)print("\n📝 Extracting specialized text color embeddings (dims 0-15)...")text_color_embeddings_spec = text_full_embeddings[:, :self.color_emb_dim] # First 16 dimsprint(f" Specialized text color embeddings shape: {text_color_embeddings_spec.shape}")text_color_metrics = self.compute_similarity_metrics(text_color_embeddings_spec, text_colors_full)# Use ensemble: combine specialized (16D) + full (512D)text_color_class = self.evaluate_classification_performance(text_color_embeddings_spec, text_colors_full,"Text Color Embeddings (Ensemble)", "Color",full_embeddings=text_full_embeddings, ensemble_weight=0.4 # 40% specialized, 60% full)text_color_metrics.update(text_color_class)results['text_color'] = text_color_metrics# Image color embeddings with ensembleprint("\n🖼️ Extracting specialized image color embeddings (dims 0-15)...")image_color_embeddings_spec = image_full_embeddings[:, :self.color_emb_dim] # First 16 dimsprint(f" Specialized image color embeddings shape: {image_color_embeddings_spec.shape}")image_color_metrics = self.compute_similarity_metrics(image_color_embeddings_spec, image_colors_full)image_color_class = self.evaluate_classification_performance(image_color_embeddings_spec, image_colors_full,"Image Color Embeddings (Ensemble)", "Color",full_embeddings=image_full_embeddings, ensemble_weight=0.4)image_color_metrics.update(image_color_class)results['image_color'] = image_color_metrics# ========== HIERARCHY EVALUATION (DIMS 16-79) WITH ENSEMBLE ==========print("\n📋 HIERARCHY EVALUATION (dims 16-79) - Using Ensemble")print("=" * 50)# Extract specialized hierarchy embeddings (dims 16-79)print("\n📝 Extracting specialized text hierarchy embeddings (dims 16-79)...")text_hierarchy_embeddings_spec = text_full_embeddings[:, self.color_emb_dim:self.color_emb_dim+self.hierarchy_emb_dim] # dims 16-79print(f" Specialized text hierarchy embeddings shape: {text_hierarchy_embeddings_spec.shape}")text_hierarchy_metrics = self.compute_similarity_metrics(text_hierarchy_embeddings_spec, text_hierarchies_full)# Use ensemble: combine specialized (64D) + full (512D)text_hierarchy_class = self.evaluate_classification_performance(text_hierarchy_embeddings_spec, text_hierarchies_full,"Text Hierarchy Embeddings (Ensemble)", "Hierarchy",full_embeddings=text_full_embeddings, ensemble_weight=0.4)text_hierarchy_metrics.update(text_hierarchy_class)results['text_hierarchy'] = text_hierarchy_metrics# Image hierarchy embeddings with ensembleprint("\n🖼️ Extracting specialized image hierarchy embeddings (dims 16-79)...")image_hierarchy_embeddings_spec = image_full_embeddings[:, self.color_emb_dim:self.color_emb_dim+self.hierarchy_emb_dim] # dims 16-79print(f" Specialized image hierarchy embeddings shape: {image_hierarchy_embeddings_spec.shape}")image_hierarchy_metrics = self.compute_similarity_metrics(image_hierarchy_embeddings_spec, image_hierarchies_full)image_hierarchy_class = self.evaluate_classification_performance(image_hierarchy_embeddings_spec, image_hierarchies_full,"Image Hierarchy Embeddings (Ensemble)", "Hierarchy",full_embeddings=image_full_embeddings, ensemble_weight=0.4)image_hierarchy_metrics.update(image_hierarchy_class)results['image_hierarchy'] = image_hierarchy_metrics# Cleanupdel text_full_embeddings, image_full_embeddingsdel text_color_embeddings_spec, image_color_embeddings_specdel text_hierarchy_embeddings_spec, image_hierarchy_embeddings_spectorch.cuda.empty_cache() if torch.cuda.is_available() else None# ========== SAVE VISUALIZATIONS ==========610 unmodified lines'trained': trained_color_img_acc,'baseline': baseline_color_img_acc,'diff': diff,'trained_dims': '0-15 (16 dims)','baseline_dims': 'All dimensions (512 dims)'})48 unmodified linesprint("\nRaisons probables:")print("\n1. 📐 CAPACITÉ DIMENSIONNELLE:")print(" • Baseline: Utilise TOUTES les 512 dimensions des embeddings")print(" • Modèle entraîné: Utilise seulement 16 dims (couleur) ou 64 dims (hiérarchie)")print(" • Impact: La baseline a accès à plus d'information pour la classification")print("\n2. 🎯 SUR-SPÉCIALISATION:")43 unmodified linesdevice = torch.device("mps" if torch.backends.mps.is_available() else "cpu")print(f"Using device: {device}")directory = 'main_model_analysis_model'max_samples = 10000evaluator = ColorHierarchyEvaluator(device=device, directory=directory)
evaluation/main_model_evaluation.py+175-53