Spaces:
Sleeping
Sleeping
Create Zero-Shot Image Classification
Browse files
Zero-Shot Image Classification
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Import necessary libraries
|
| 2 |
+
from transformers import AutoProcessor, AutoModelForZeroShotImageClassification
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import requests
|
| 5 |
+
import torch
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
|
| 8 |
+
# Load the pre-trained model and processor
|
| 9 |
+
checkpoint = "openai/clip-vit-large-patch14"
|
| 10 |
+
model = AutoModelForZeroShotImageClassification.from_pretrained(checkpoint)
|
| 11 |
+
processor = AutoProcessor.from_pretrained(checkpoint)
|
| 12 |
+
|
| 13 |
+
# Load and display the image
|
| 14 |
+
url = "URL_of_the_image"
|
| 15 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
| 16 |
+
plt.imshow(image)
|
| 17 |
+
plt.show()
|
| 18 |
+
|
| 19 |
+
# Specify candidate labels for zero-shot classification
|
| 20 |
+
candidate_labels = ["tree", "car", "bike", "cat"]
|
| 21 |
+
|
| 22 |
+
# Prepare inputs for the model
|
| 23 |
+
inputs = processor(text=candidate_labels, images=image, return_tensors="pt", padding=True)
|
| 24 |
+
|
| 25 |
+
# Make predictions
|
| 26 |
+
outputs = model(**inputs)
|
| 27 |
+
logits = outputs.logits_per_image # shape: [batch_size, num_classes]
|
| 28 |
+
probs = logits.softmax(dim=1) # Convert to probabilities
|
| 29 |
+
|
| 30 |
+
# Get and print the most likely class
|
| 31 |
+
predicted_class_idx = probs.argmax(-1).item()
|
| 32 |
+
predicted_class = candidate_labels[predicted_class_idx]
|
| 33 |
+
print(f'Predicted class: {predicted_class}')
|