Views
No views yet
ViT-B/16) model trained to classify 14 different shark species using image data.google/vit-base-patch16-224-in21k backbone.| Item | Details |
|---|---|
| Base Model | google/vit-base-patch16-224-in21k |
| Fine-tuned on | 14 Shark Classes |
| Train Samples | 1395 |
| Validation Samples | 295 |
| Test Samples | 313 |
| Framework | PyTorch + Hugging Face Transformers |
| Processor | ViTImageProcessor |
| Epochs Trained | 5 |
| Test Accuracy | 88.18% |
| Test Loss | 0.7288 |
ViTImageProcessor with resizing, normalization, and label mapping.| Epoch | Training Loss | Validation Loss | Accuracy |
|---|---|---|---|
| 1 | 1.8651 | 1.7818 | 69.83% |
| 2 | 1.1247 | 1.2082 | 85.08% |
| 3 | 0.7594 | 0.9216 | 86.78% |
| 4 | 0.4500 | 0.7947 | 87.12% |
| 5 | 0.3931 | 0.7611 | 88.81% ✅ |

1from transformers import ViTForImageClassification, ViTImageProcessor
2from PIL import Image as PILImage
3import torch
4
5# المسار الذي تم حفظ النموذج فيه
6model_path = "./vit-shark-model"
7
8# تحميل المعالج والنموذج
9image_processor = ViTImageProcessor.from_pretrained(model_path)
10model = ViTForImageClassification.from_pretrained(model_path)
11
12# (اختياري) نقل النموذج لوحدة المعالجة الرسومية (GPU)
13device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14model.to(device)
15model.eval() # وضع التقييم
16
17# مثال: معالجة صورة وتوقعها
18image = PILImage.open("path/to/your/shark_image.jpg").convert("RGB")
19inputs = image_processor(images=image, return_tensors="pt").to(device)
20
21with torch.no_grad():
22 outputs = model(**inputs)
23
24logits = outputs.logits
25predicted_class_idx = logits.argmax(-1).item()
26predicted_label = model.config.id2label[predicted_class_idx]
27
28print(f"Predicted class: {predicted_label}")1!pip install gradio transformers torch torchvision
2
3import gradio as gr
4from transformers import pipeline
5import torch
6from torchvision import transforms
7from PIL import Image
8
9# Load the model
10try:
11 classifier = pipeline("image-classification", model="HatemMoushir/DeepShark-ViT-Hatem-V1")
12except Exception as e:
13 print(f"Error loading model: {e}")
14 print("Please ensure you have access to the model or that the model name is correct.")
15 # Fallback or exit if model can't be loaded
16 exit()
17
18# Define a function to make predictions
19def predict_shark_species(image):
20 if image is None:
21 return "Please upload an image."
22
23 # The pipeline handles preprocessing, but sometimes explicit conversion helps
24 # Ensure the image is in RGB format if it's not already
25 if image.mode != 'RGB':
26 image = image.convert('RGB')
27
28 # Make prediction
29 # The output is a list of dictionaries, e.g., [{'score': 0.99, 'label': 'Great White Shark'}]
30 predictions = classifier(image)
31
32 # Format the output
33 if predictions:
34 # Get the top prediction
35 top_prediction = predictions[0]
36 label = top_prediction['label'].replace('_', ' ').title() # Format label nicely
37 score = top_prediction['score'] * 100 # Convert to percentage
38
39 if score < 50:
40 return "Prediction: Unknown (Low confidence)"
41 else:
42 return f"Prediction: **{label}**\nConfidence: **{score:.2f}%**"
43 else:
44 return "No prediction could be made."
45
46# Create the Gradio interface
47iface = gr.Interface(
48 fn=predict_shark_species,
49 inputs=gr.Image(type="pil", label="Upload Shark Image"),
50 outputs="markdown",
51 title="🦈 DeepShark-ViT-Hatem-V1: Shark Species Classifier",
52 description="Upload an image of a shark to get a prediction of its species using the HatemMoushir/DeepShark-ViT-Hatem-V1 model.",
53 examples=[
54 # You can add example image paths here if you have them locally
55 # e.g., ["path/to/your/shark_example1.jpg"]
56 ]
57)
58
59# Launch the interface
60if __name__ == "__main__":
61 print("Starting Gradio interface...")
62 iface.launch(share=True) # Set share=True to get a public link (useful for sharing)
63