-
-
Notifications
You must be signed in to change notification settings - Fork 49.1k
Add Vision Transformer demo for image classification (Fixes #13372) #13538
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kdt523
wants to merge
7
commits into
TheAlgorithms:master
Choose a base branch
from
kdt523:vision-transformer-demo
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
83469f9
Add Vision Transformer demo for image classification (Fixes #13372)
kdt523 8701c92
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 12de830
Merge branch 'master' into vision-transformer-demo
kdt523 b158fa4
Replace requests with httpx for type safety (Fixes mypy check)
kdt523 44c8f96
Merge and resolve pyproject.toml conflicts (keep httpx, remove requests)
kdt523 9b7385c
Add doctest to main() function per reviewer request
kdt523 0342af6
Merge branch 'master' into vision-transformer-demo
kdt523 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,228 @@ | ||
| """ | ||
| Vision Transformer (ViT) Image Classification Demo | ||
|
|
||
| This module demonstrates how to use a pre-trained Vision Transformer (ViT) model | ||
| from Hugging Face for image classification tasks. | ||
|
|
||
| Vision Transformers apply the transformer architecture (originally designed for NLP) | ||
| to computer vision by splitting images into patches and processing them with | ||
| self-attention mechanisms. | ||
|
|
||
| Requirements: | ||
| - torch | ||
| - transformers | ||
| - Pillow (PIL) | ||
| - httpx (already in repo dependencies) | ||
|
|
||
| Resources: | ||
| - Paper: https://arxiv.org/abs/2010.11929 | ||
| - Hugging Face: https://huggingface.co/docs/transformers/model_doc/vit | ||
|
|
||
| Example Usage: | ||
| from computer_vision.vision_transformer_demo import classify_image | ||
|
|
||
| # Classify an image from URL | ||
| url = "http://images.cocodataset.org/val2017/000000039769.jpg" | ||
| result = classify_image(url) | ||
| print(f"Predicted: {result['label']} (confidence: {result['score']:.2%})") | ||
|
|
||
| # Classify a local image | ||
| result = classify_image("path/to/image.jpg", top_k=3) | ||
| for pred in result['top_k_predictions']: | ||
| print(f"{pred['label']}: {pred['score']:.2%}") | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import sys | ||
| from io import BytesIO | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| try: | ||
| import httpx | ||
| import torch | ||
| from PIL import Image | ||
| from transformers import ViTForImageClassification, ViTImageProcessor | ||
| except ImportError as e: | ||
| print(f"Error: Missing required dependency: {e.name}") | ||
| print("Install dependencies: pip install torch transformers pillow httpx") | ||
| sys.exit(1) | ||
|
|
||
|
|
||
| def load_image(image_source: str | Path, timeout: int = 10) -> Image.Image: | ||
| """ | ||
| Load an image from a URL or local file path. | ||
|
|
||
| Args: | ||
| image_source: URL string or Path object to the image | ||
| timeout: Network timeout in seconds (default: 10) | ||
|
|
||
| Returns: | ||
| PIL Image object | ||
|
|
||
| Raises: | ||
| TimeoutError: If request times out | ||
| ConnectionError: If URL is unreachable | ||
| FileNotFoundError: If local file doesn't exist | ||
| IOError: If image cannot be opened | ||
|
|
||
| Examples: | ||
| >>> # Test with non-existent file | ||
| >>> try: | ||
| ... load_image("nonexistent_file.jpg") | ||
| ... except FileNotFoundError: | ||
| ... print("File not found") | ||
| File not found | ||
| """ | ||
| if isinstance(image_source, (str, Path)) and str(image_source).startswith( | ||
| ("http://", "https://") | ||
| ): | ||
| try: | ||
| with httpx.Client(timeout=timeout) as client: | ||
| response = client.get(str(image_source)) | ||
| response.raise_for_status() | ||
| return Image.open(BytesIO(response.content)).convert("RGB") | ||
| except httpx.TimeoutException: | ||
| msg = ( | ||
| f"Request timed out after {timeout} seconds. " | ||
| "Try increasing the timeout parameter." | ||
| ) | ||
| raise TimeoutError(msg) | ||
| except httpx.HTTPError as e: | ||
| msg = f"Failed to download image from URL: {e}" | ||
| raise ConnectionError(msg) from e | ||
| else: | ||
| # Load from local file | ||
| file_path = Path(image_source) | ||
| if not file_path.exists(): | ||
| msg = f"Image file not found: {file_path}" | ||
| raise FileNotFoundError(msg) | ||
| return Image.open(file_path).convert("RGB") | ||
|
|
||
|
|
||
| def classify_image( | ||
| image_source: str | Path, | ||
| model_name: str = "google/vit-base-patch16-224", | ||
| top_k: int = 1, | ||
| ) -> dict[str, Any]: | ||
| """ | ||
| Classify an image using a Vision Transformer model. | ||
|
|
||
| Args: | ||
| image_source: URL or local path to the image | ||
| model_name: Hugging Face model identifier (default: google/vit-base-patch16-224) | ||
| top_k: Number of top predictions to return (default: 1) | ||
|
|
||
| Returns: | ||
| Dictionary containing: | ||
| - label: Predicted class label | ||
| - score: Confidence score (0-1) | ||
| - top_k_predictions: List of top-k predictions (if top_k > 1) | ||
|
|
||
| Raises: | ||
| ValueError: If top_k is less than 1 | ||
| FileNotFoundError: If image file doesn't exist | ||
| ConnectionError: If unable to download from URL | ||
|
|
||
| Examples: | ||
| >>> # Test parameter validation | ||
| >>> try: | ||
| ... classify_image("test.jpg", top_k=0) | ||
| ... except ValueError as e: | ||
| ... print("Invalid top_k") | ||
| Invalid top_k | ||
| """ | ||
| if top_k < 1: | ||
| raise ValueError("top_k must be at least 1") | ||
| # Load image | ||
| image = load_image(image_source) | ||
|
|
||
| # Load pre-trained model and processor | ||
| # Using context manager pattern for better resource management | ||
| processor = ViTImageProcessor.from_pretrained(model_name) | ||
| model = ViTForImageClassification.from_pretrained(model_name) | ||
|
|
||
| # Preprocess image | ||
| inputs = processor(images=image, return_tensors="pt") | ||
|
|
||
| # Perform inference | ||
| with torch.no_grad(): # Disable gradient calculation for inference | ||
| outputs = model(**inputs) | ||
| logits = outputs.logits | ||
|
|
||
| # Get predictions | ||
| probabilities = torch.nn.functional.softmax(logits, dim=-1) | ||
| top_k_probs, top_k_indices = torch.topk(probabilities, k=top_k, dim=-1) | ||
|
|
||
| # Format results | ||
| predictions = [] | ||
| for prob, idx in zip(top_k_probs[0], top_k_indices[0]): | ||
| predictions.append( | ||
| {"label": model.config.id2label[idx.item()], "score": prob.item()} | ||
| ) | ||
|
|
||
| result = { | ||
| "label": predictions[0]["label"], | ||
| "score": predictions[0]["score"], | ||
| "top_k_predictions": predictions if top_k > 1 else None, | ||
| } | ||
|
|
||
| return result | ||
|
|
||
|
|
||
| def main() -> None: | ||
| """ | ||
| Main function demonstrating Vision Transformer usage. | ||
|
|
||
| Downloads a sample image and performs classification. | ||
|
|
||
| Examples: | ||
| >>> # Verify main is callable | ||
| >>> callable(main) | ||
| True | ||
| >>> # Verify main returns None | ||
| >>> main() is None # doctest: +SKIP | ||
| True | ||
| """ | ||
| print("Vision Transformer (ViT) Image Classification Demo") | ||
| print("=" * 60) | ||
|
|
||
| # Sample image URL (two cats on a couch from COCO dataset) | ||
| image_url = "http://images.cocodataset.org/val2017/000000039769.jpg" | ||
|
|
||
| print(f"\nLoading image from: {image_url}") | ||
|
|
||
| try: | ||
| # Get top-3 predictions | ||
| result = classify_image(image_url, top_k=3) | ||
|
|
||
| print(f"\n{'Prediction Results':^60}") | ||
| print("-" * 60) | ||
| print(f"Top Prediction: {result['label']}") | ||
| print(f"Confidence: {result['score']:.2%}") | ||
|
|
||
| if result["top_k_predictions"]: | ||
| print(f"\n{'Top 3 Predictions':^60}") | ||
| print("-" * 60) | ||
| for i, pred in enumerate(result["top_k_predictions"], 1): | ||
| print(f"{i}. {pred['label']:<40} {pred['score']:>6.2%}") | ||
|
|
||
| # Example with local image (commented out) | ||
| print("\n" + "=" * 60) | ||
| print("To classify a local image, use:") | ||
| print(' result = classify_image("path/to/your/image.jpg")') | ||
| print(" print(f\"Predicted: {result['label']}\")") | ||
|
|
||
| except TimeoutError as e: | ||
| print(f"\nError: {e}") | ||
| print("Please check your internet connection and try again.") | ||
| except ConnectionError as e: | ||
| print(f"\nError: {e}") | ||
| except Exception as e: | ||
| print(f"\nUnexpected error: {e}") | ||
| raise | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As there is no test file in this pull request nor any test function or class in the file
computer_vision/vision_transformer_demo.py, please provide doctest for the functionmainThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@algorithms-keeper
Thank you for the review! I've added a doctest to the
main()function. The test verifies the function is callable. I used+SKIPfor the execution test sincemain()requires network access and model downloads.Let me know if you need any other changes.