File size: 6,485 Bytes
91219fd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | {
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import pipeline\n",
"\n",
"checkpoint = \"openai/clip-vit-large-patch14\"\n",
"detector = pipeline(model=checkpoint, task=\"zero-shot-image-classification\")\n",
"#checkpoint = \"google/siglip-so400m-patch14-384\"\n",
"#detector = pipeline(task=\"zero-shot-image-classification\", model=\"google/siglip-so400m-patch14-384\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datasets import load_dataset\n",
"\n",
"dataset = load_dataset('pcuenq/oxford-pets')\n",
"dataset"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dataset['train'][0]['image']"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from PIL import Image\n",
"import io\n",
"from tqdm import tqdm\n",
"\n",
"labels_oxford_pets = ['Siamese', 'Birman', 'shiba inu', 'staffordshire bull terrier', 'basset hound', 'Bombay', 'japanese chin', 'chihuahua', 'german shorthaired', 'pomeranian', 'beagle', 'english cocker spaniel', 'american pit bull terrier', 'Ragdoll', 'Persian', 'Egyptian Mau', 'miniature pinscher', 'Sphynx', 'Maine Coon', 'keeshond', 'yorkshire terrier', 'havanese', 'leonberger', 'wheaten terrier', 'american bulldog', 'english setter', 'boxer', 'newfoundland', 'Bengal', 'samoyed', 'British Shorthair', 'great pyrenees', 'Abyssinian', 'pug', 'saint bernard', 'Russian Blue', 'scottish terrier']\n",
"\n",
"# List to store true labels and predicted labels\n",
"true_labels = []\n",
"predicted_labels = []"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"for i in tqdm(range(len(dataset['train']))):\n",
" # Get the image bytes from the dataset\n",
" image_bytes = dataset['train'][i]['image']['bytes']\n",
" \n",
" # Convert the bytes to a PIL image\n",
" image = Image.open(io.BytesIO(image_bytes))\n",
" \n",
" # Run the detector on the image with the provided labels\n",
" results = detector(image, candidate_labels=labels_oxford_pets)\n",
" # Sort the results by score in descending order\n",
" sorted_results = sorted(results, key=lambda x: x['score'], reverse=True)\n",
" \n",
" # Get the top predicted label\n",
" predicted_label = sorted_results[0]['label']\n",
" \n",
" # Append the true and predicted labels to the respective lists\n",
" true_labels.append(dataset['train'][i]['label'])\n",
" predicted_labels.append(predicted_label)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import accuracy_score, precision_score, recall_score\n",
"\n",
"# Calculate accuracy\n",
"accuracy = accuracy_score(true_labels, predicted_labels)\n",
"\n",
"# Calculate precision and recall\n",
"precision = precision_score(true_labels, predicted_labels, average='weighted', labels=labels_oxford_pets)\n",
"recall = recall_score(true_labels, predicted_labels, average='weighted', labels=labels_oxford_pets)\n",
"\n",
"# Print the results\n",
"print(f\"Accuracy: {accuracy:.4f}\")\n",
"print(f\"Precision: {precision:.4f}\")\n",
"print(f\"Recall: {recall:.4f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Gradio example"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import gradio as gr\n",
"from transformers import pipeline\n",
"\n",
"# Load models\n",
"vit_classifier = pipeline(\"image-classification\", model=\"kuhs/vit-base-oxford-iiit-pets\")\n",
"clip_detector = pipeline(model=\"openai/clip-vit-large-patch14\", task=\"zero-shot-image-classification\")\n",
"\n",
"labels_oxford_pets = [\n",
" 'Siamese', 'Birman', 'shiba inu', 'staffordshire bull terrier', 'basset hound', 'Bombay', 'japanese chin',\n",
" 'chihuahua', 'german shorthaired', 'pomeranian', 'beagle', 'english cocker spaniel', 'american pit bull terrier',\n",
" 'Ragdoll', 'Persian', 'Egyptian Mau', 'miniature pinscher', 'Sphynx', 'Maine Coon', 'keeshond', 'yorkshire terrier',\n",
" 'havanese', 'leonberger', 'wheaten terrier', 'american bulldog', 'english setter', 'boxer', 'newfoundland', 'Bengal',\n",
" 'samoyed', 'British Shorthair', 'great pyrenees', 'Abyssinian', 'pug', 'saint bernard', 'Russian Blue', 'scottish terrier'\n",
"]\n",
"\n",
"def classify_pet(image):\n",
" vit_results = vit_classifier(image)\n",
" vit_output = {result['label']: result['score'] for result in vit_results}\n",
" \n",
" clip_results = clip_detector(image, candidate_labels=labels_oxford_pets)\n",
" clip_output = {result['label']: result['score'] for result in clip_results}\n",
" \n",
" return {\"ViT Classification\": vit_output, \"CLIP Zero-Shot Classification\": clip_output}\n",
"\n",
"example_images = [\n",
" [\"example_images/dog1.jpeg\"],\n",
" [\"example_images/dog2.jpeg\"],\n",
" [\"example_images/leonberger.jpg\"],\n",
" [\"example_images/snow_leopard.jpeg\"],\n",
" [\"example_images/cat.jpg\"]\n",
"]\n",
"\n",
"iface = gr.Interface(\n",
" fn=classify_pet,\n",
" inputs=gr.Image(type=\"filepath\"),\n",
" outputs=gr.JSON(),\n",
" title=\"Pet Classification Comparison\",\n",
" description=\"Upload an image of a pet, and compare results from a trained ViT model and a zero-shot CLIP model.\",\n",
" examples=example_images\n",
")\n",
"\n",
"iface.launch()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|