Views
No views yet
nlpconnect/vit-gpt2-image-captioning, trained on the CUB-200-2011 dataset for bird species classification and image captioning.nlpconnect/vit-gpt2-image-captioning)model.safetensors: Trained model weightsconfig.json: Model configurationpreprocessor_config.json: ViTImageProcessor settingstokenizer_config.json, vocab.json: GPT2 tokenizer filesspecies_mapping.txt: Mapping of class indices to bird species namescub200_captions.csv: Generated captions for the datasetmodel.py: Custom BirdCaptioningModel class definitionpip install transformers torch huggingface_hub1from transformers import ViTImageProcessor, AutoTokenizer
2from huggingface_hub import PyTorchModelHubMixin
3import torch
4from model import BirdCaptioningModel # Save model.py locally
5
6# Set device
7device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8
9# Load model
10model = BirdCaptioningModel.from_pretrained("INVERTO/bird-captioning-cub200").to(device)
11image_processor = ViTImageProcessor.from_pretrained("INVERTO/bird-captioning-cub200")
12tokenizer = AutoTokenizer.from_pretrained("INVERTO/bird-captioning-cub200")
13model.eval()
14
15# Load species mapping
16species_mapping = {}
17with open("species_mapping.txt", "r") as f:
18 for line in f:
19 idx, name = line.strip().split(",", 1)
20 species_mapping[int(idx)] = name1from PIL import Image
2
3def predict_bird_image(image_path):
4 image = Image.open(image_path).convert("RGB")
5 pixel_values = image_processor(image, return_tensors="pt").pixel_values.to(device)
6 with torch.no_grad():
7 output_ids = model.base_model.generate(pixel_values, max_length=75, num_beams=4)
8 _, class_logits = model(pixel_values)
9 predicted_class_idx = torch.argmax(class_logits, dim=1).item()
10 confidence = torch.nn.functional.softmax(class_logits, dim=1)[0, predicted_class_idx].item() * 100
11 caption = tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
12 species = species_mapping.get(predicted_class_idx, "Unknown")
13 return caption, species, confidence
14
15# Example
16caption, species, confidence = predict_bird_image("/kaggle/input/cub2002011/CUB_200_2011/images/006.Least_Auklet/Least_Auklet_0007_795123.jpg")
17print(f"Caption: {caption}")
18print(f"Species: {species}")
19print(f"Confidence: {confidence:.2f}%")