source
stringclasses
470 values
url
stringlengths
49
167
file_type
stringclasses
1 value
chunk
stringlengths
1
512
chunk_id
stringlengths
5
9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/semantic_segmentation.md
https://huggingface.co/docs/transformers/en/tasks/semantic_segmentation/#inference
.md
>>> img = np.array(image) * 0.5 + color_seg * 0.5 # plot the image with the segmentation map >>> img = img.astype(np.uint8) >>> plt.figure(figsize=(15, 10)) >>> plt.imshow(img) >>> plt.show() ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/mai...
78_9_15
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/
.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
79_0_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/
.md
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered ...
79_0_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#image-captioning
.md
[[open-in-colab]] Image captioning is the task of predicting a caption for a given image. Common real world applications of it include aiding visually impaired people that can help them navigate through different situations. Therefore, image captioning helps to improve content accessibility for people by describing i...
79_1_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#image-captioning
.md
This guide will show you how to: * Fine-tune an image captioning model. * Use the fine-tuned model for inference. Before you begin, make sure you have all the necessary libraries installed: ```bash pip install transformers datasets evaluate -q pip install jiwer -q ``` We encourage you to log in to your Hugging ...
79_1_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#image-captioning
.md
notebook_login() ```
79_1_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#load-the-pokémon-blip-captions-dataset
.md
Use the 🤗 Dataset library to load a dataset that consists of {image-caption} pairs. To create your own image captioning dataset in PyTorch, you can follow [this notebook](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/GIT/Fine_tune_GIT_on_an_image_captioning_dataset.ipynb). ```python from datasets ...
79_2_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#load-the-pokémon-blip-captions-dataset
.md
ds = load_dataset("lambdalabs/pokemon-blip-captions") ds ``` ```bash DatasetDict({ train: Dataset({ features: ['image', 'text'], num_rows: 833 }) }) ``` The dataset has two features, `image` and `text`. <Tip> Many image captioning datasets contain multiple captions per image. In those cases, a common strategy is ...
79_2_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#load-the-pokémon-blip-captions-dataset
.md
</Tip> Split the dataset’s train split into a train and test set with the [`~datasets.Dataset.train_test_split`] method: ```python ds = ds["train"].train_test_split(test_size=0.1) train_ds = ds["train"] test_ds = ds["test"] ``` Let's visualize a couple of samples from the training set. ```python from textwrap i...
79_2_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#load-the-pokémon-blip-captions-dataset
.md
def plot_images(images, captions): plt.figure(figsize=(20, 20)) for i in range(len(images)): ax = plt.subplot(1, len(images), i + 1) caption = captions[i] caption = "\n".join(wrap(caption, 12)) plt.title(caption) plt.imshow(images[i]) plt.axis("off")
79_2_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#load-the-pokémon-blip-captions-dataset
.md
sample_images_to_visualize = [np.array(train_ds[i]["image"]) for i in range(5)] sample_captions = [train_ds[i]["text"] for i in range(5)] plot_images(sample_images_to_visualize, sample_captions) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/ma...
79_2_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#preprocess-the-dataset
.md
Since the dataset has two modalities (image and text), the pre-processing pipeline will preprocess images and the captions. To do so, load the processor class associated with the model you are about to fine-tune. ```python from transformers import AutoProcessor
79_3_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#preprocess-the-dataset
.md
checkpoint = "microsoft/git-base" processor = AutoProcessor.from_pretrained(checkpoint) ``` The processor will internally pre-process the image (which includes resizing, and pixel scaling) and tokenize the caption. ```python def transforms(example_batch): images = [x for x in example_batch["image"]] captions = [x f...
79_3_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#preprocess-the-dataset
.md
train_ds.set_transform(transforms) test_ds.set_transform(transforms) ``` With the dataset ready, you can now set up the model for fine-tuning.
79_3_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#load-a-base-model
.md
Load the ["microsoft/git-base"](https://huggingface.co/microsoft/git-base) into a [`AutoModelForCausalLM`](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoModelForCausalLM) object. ```python from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained(checkpoint...
79_4_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#evaluate
.md
Image captioning models are typically evaluated with the [Rouge Score](https://huggingface.co/spaces/evaluate-metric/rouge) or [Word Error Rate](https://huggingface.co/spaces/evaluate-metric/wer). For this guide, you will use the Word Error Rate (WER). We use the 🤗 Evaluate library to do so. For potential limitation...
79_5_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#evaluate
.md
wer = load("wer") def compute_metrics(eval_pred): logits, labels = eval_pred predicted = logits.argmax(-1) decoded_labels = processor.batch_decode(labels, skip_special_tokens=True) decoded_predictions = processor.batch_decode(predicted, skip_special_tokens=True) wer_score = wer.compute(predictions=decoded_predictions...
79_5_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#train
.md
Now, you are ready to start fine-tuning the model. You will use the 🤗 [`Trainer`] for this. First, define the training arguments using [`TrainingArguments`]. ```python from transformers import TrainingArguments, Trainer model_name = checkpoint.split("/")[1]
79_6_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#train
.md
training_args = TrainingArguments( output_dir=f"{model_name}-pokemon", learning_rate=5e-5, num_train_epochs=50, fp16=True, per_device_train_batch_size=32, per_device_eval_batch_size=32, gradient_accumulation_steps=2, save_total_limit=3, eval_strategy="steps", eval_steps=50, save_strategy="steps", save_steps=50, logging...
79_6_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#train
.md
load_best_model_at_end=True, ) ``` Then pass them along with the datasets and the model to 🤗 Trainer. ```python trainer = Trainer( model=model, args=training_args, train_dataset=train_ds, eval_dataset=test_ds, compute_metrics=compute_metrics, ) ``` To start training, simply call [`~Trainer.train`] on the [`Train...
79_6_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#train
.md
```python trainer.train() ``` You should see the training loss drop smoothly as training progresses. Once training is completed, share your model to the Hub with the [`~Trainer.push_to_hub`] method so everyone can use your model: ```python trainer.push_to_hub() ```
79_6_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#inference
.md
Take a sample image from `test_ds` to test the model. ```python from PIL import Image import requests
79_7_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#inference
.md
url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png" image = Image.open(requests.get(url, stream=True).raw) image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/test_image_image_cap....
79_7_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#inference
.md
</div> Prepare image for the model. ```python from accelerate.test_utils.testing import get_backend # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) device, _, _ = get_backend() inputs = processor(images=image, return_tensors="pt").to(device) pixel_values = inputs.pixel_values ``` Ca...
79_7_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_captioning.md
https://huggingface.co/docs/transformers/en/tasks/image_captioning/#inference
.md
```python generated_ids = model.generate(pixel_values=pixel_values, max_length=50) generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] print(generated_caption) ``` ```bash a drawing of a pink and blue pokemon ``` Looks like the fine-tuned model generated a pretty good caption!
79_7_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/
.md
<!--Copyright 2024 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
80_0_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/
.md
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered ...
80_0_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
[[open-in-colab]] Image-text-to-text models, also known as vision language models (VLMs), are language models that take an image input. These models can tackle various tasks, from visual question answering to image segmentation. This task shares many similarities with image-to-text, butwith some overlapping use cases...
80_1_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
In this guide, we provide a brief overview of VLMs and show how to use them with Transformers for inference. To begin with, there are multiple types of VLMs: - base models used for fine-tuning - chat fine-tuned models for conversation - instruction fine-tuned models This guide focuses on inference with an instructi...
80_1_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
```bash pip install -q transformers accelerate flash_attn ``` Let's initialize the model and the processor. ```python from transformers import AutoProcessor, AutoModelForImageTextToText import torch
80_1_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
device = torch.device("cuda") model = AutoModelForImageTextToText.from_pretrained( "HuggingFaceM4/idefics2-8b", torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2", ).to(device)
80_1_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
processor = AutoProcessor.from_pretrained("HuggingFaceM4/idefics2-8b") ``` This model has a [chat template](./chat_templating) that helps user parse chat outputs. Moreover, the model can also accept multiple images as input in a single conversation or message. We will now prepare the inputs. The image inputs look l...
80_1_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
</div> <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg" alt="A bee on a pink flower"/> </div> ```python from PIL import Image import requests
80_1_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
img_urls =["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"] images = [Image.open(requests.get(img_urls[0], stream=True).raw), Image.open(requests.get(img_urls[1], stream=True).raw)] ``` Be...
80_1_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
```python messages = [ { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text": "What do we see in this image?"}, ] }, { "role": "assistant", "content": [ {"type": "text", "text": "In this image we can see two cats on the nets."}, ] }, { "role": "user", "content": [ {"type": "image"}, {"type": "text",...
80_1_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
```python prompt = processor.apply_chat_template(messages, add_generation_prompt=True) inputs = processor(text=prompt, images=[images[0], images[1]], return_tensors="pt").to(device) ``` We can now pass the preprocessed inputs to the model. ```python with torch.no_grad(): generated_ids = model.generate(**inputs, max...
80_1_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#image-text-to-text
.md
print(generated_texts) ## ['User: What do we see in this image? \nAssistant: In this image we can see two cats on the nets. \nUser: And how about this image? \nAssistant: In this image we can see flowers, plants and insect.'] ```
80_1_9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#pipeline
.md
The fastest way to get started is to use the [`Pipeline`] API. Specify the `"image-text-to-text"` task and the model you want to use. ```python from transformers import pipeline pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf") ``` The example below uses chat templates to format ...
80_2_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#pipeline
.md
{ "type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg", }, {"type": "text", "text": "Describe this image."}, ], }, { "role": "assistant", "content": [ {"type": "text", "text": "There's a pink flower"}, ], }, ] ``` Pass the chat template formatted text and i...
80_2_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#pipeline
.md
```python outputs = pipe(text=messages, max_new_tokens=20, return_full_text=False) outputs[0]["generated_text"] # with a yellow center in the foreground. The flower is surrounded by red and white flowers with green stems ```
80_2_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#streaming
.md
We can use [text streaming](./generation_strategies#streaming) for a better generation experience. Transformers supports streaming with the [`TextStreamer`] or [`TextIteratorStreamer`] classes. We will use the [`TextIteratorStreamer`] with IDEFICS-8B.
80_3_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#streaming
.md
Assume we have an application that keeps chat history and takes in the new user input. We will preprocess the inputs as usual and initialize [`TextIteratorStreamer`] to handle the generation in a separate thread. This allows you to stream the generated text tokens in real-time. Any generation arguments can be passed to...
80_3_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#streaming
.md
def model_inference( user_prompt, chat_history, max_new_tokens, images ): user_prompt = { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text": user_prompt}, ] } chat_history.append(user_prompt) streamer = TextIteratorStreamer( processor.tokenizer, skip_prompt=True, timeout=5.0, ) generation_args = ...
80_3_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#streaming
.md
generation_args = { "max_new_tokens": max_new_tokens, "streamer": streamer, "do_sample": False } # add_generation_prompt=True makes model generate bot response prompt = processor.apply_chat_template(chat_history, add_generation_prompt=True) inputs = processor( text=prompt, images=images, return_tensors="pt", ).to(devi...
80_3_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#streaming
.md
thread = Thread( target=model.generate, kwargs=generation_args, ) thread.start() acc_text = "" for text_token in streamer: time.sleep(0.04) acc_text += text_token if acc_text.endswith("<end_of_utterance>"): acc_text = acc_text[:-18] yield acc_text thread.join() ``` Now let's call the `model_inference` function we c...
80_3_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#streaming
.md
for value in generator: print(value) # In # In this # In this image ... ```
80_3_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#fit-models-in-smaller-hardware
.md
VLMs are often large and need to be optimized to fit on smaller hardware. Transformers supports many model quantization libraries, and here we will only show int8 quantization with [Quanto](./quantization/quanto#quanto). int8 quantization offers memory improvements up to 75 percent (if all weights are quantized). Howev...
80_4_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#fit-models-in-smaller-hardware
.md
First, install dependencies. ```bash pip install -U quanto bitsandbytes ``` To quantize a model during loading, we need to first create [`QuantoConfig`]. Then load the model as usual, but pass `quantization_config`during model initialization. ```python from transformers import AutoModelForImageTextToText, QuantoC...
80_4_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#fit-models-in-smaller-hardware
.md
model_id = "HuggingFaceM4/idefics2-8b" quantization_config = QuantoConfig(weights="int8") quantized_model = AutoModelForImageTextToText.from_pretrained( model_id, device_map="cuda", quantization_config=quantization_config ) ``` And that's it, we can use the model the same way with no changes.
80_4_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/image_text_to_text.md
https://huggingface.co/docs/transformers/en/tasks/image_text_to_text/#further-reading
.md
Here are some more resources for the image-text-to-text task. - [Image-text-to-texttask page](https://huggingface.co/tasks/image-text-to-text) covers model types, use cases, datasets, and more. - [Vision Language Models Explained](https://huggingface.co/blog/vlms) is a blog post that covers everything about vision la...
80_5_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/
.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
81_0_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/
.md
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered ...
81_0_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#object-detection
.md
[[open-in-colab]] Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects, e...
81_1_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#object-detection
.md
be present in different parts of an image (e.g. the image can have several cars). This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights. Other applications include counting objects in images, image search, and more. In this guide, you will learn how to:...
81_1_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#object-detection
.md
1. Finetune [DETR](https://huggingface.co/docs/transformers/model_doc/detr), a model that combines a convolutional backbone with an encoder-decoder Transformer, on the [CPPE-5](https://huggingface.co/datasets/cppe-5) dataset. 2. Use your finetuned model for inference. <Tip> To see all architectures and checkpoints ...
81_1_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#object-detection
.md
</Tip> Before you begin, make sure you have all the necessary libraries installed: ```bash pip install -q datasets transformers accelerate timm pip install -q -U albumentations>=1.4.5 torchmetrics pycocotools ``` You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your mod...
81_1_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#object-detection
.md
We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub. When prompted, enter your token to log in: ```py >>> from huggingface_hub import notebook_login
81_1_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#object-detection
.md
>>> notebook_login() ``` To get started, we'll define global constants, namely the model name and image size. For this tutorial, we'll use the conditional DETR model due to its faster convergence. Feel free to select any object detection model available in the `transformers` library. ```py >>> MODEL_NAME = "microso...
81_1_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
The [CPPE-5 dataset](https://huggingface.co/datasets/cppe-5) contains images with annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic. Start by loading the dataset and creating a `validation` split from `train`: ```py >>> from datasets import load_dataset >>>...
81_2_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
>>> cppe5 = load_dataset("cppe-5") >>> if "validation" not in cppe5: ... split = cppe5["train"].train_test_split(0.15, seed=1337) ... cppe5["train"] = split["train"] ... cppe5["validation"] = split["test"]
81_2_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
>>> cppe5 DatasetDict({ train: Dataset({ features: ['image_id', 'image', 'width', 'height', 'objects'], num_rows: 850 }) test: Dataset({ features: ['image_id', 'image', 'width', 'height', 'objects'], num_rows: 29 }) validation: Dataset({ features: ['image_id', 'image', 'width', 'height', 'objects'], num_rows: 150 }) })...
81_2_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
To get familiar with the data, explore what the examples look like. ```py >>> cppe5["train"][0] { 'image_id': 366, 'image': <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=500x290>, 'width': 500, 'height': 500, 'objects': { 'id': [1932, 1933, 1934], 'area': [27063, 34200, 32431], 'bbox': [[29.0, 11.0, 97.0, 279...
81_2_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
'category': [0, 0, 0] } } ``` The examples in the dataset have the following fields: - `image_id`: the example image id - `image`: a `PIL.Image.Image` object containing the image - `width`: width of the image - `height`: height of the image - `objects`: a dictionary containing bounding box metadata for the objects in...
81_2_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
- `id`: the annotation id - `area`: the area of the bounding box - `bbox`: the object's bounding box (in the [COCO format](https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco) ) - `category`: the object's category, with possible values including `Coverall (0)`, `Face_Shield (1)`, `Gloves (2...
81_2_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
You may notice that the `bbox` field follows the COCO format, which is the format that the DETR model expects. However, the grouping of the fields inside `objects` differs from the annotation format DETR requires. You will need to apply some preprocessing transformations before using this data for training. To get an...
81_2_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
>>> image = cppe5["train"][2]["image"] >>> annotations = cppe5["train"][2]["objects"] >>> draw = ImageDraw.Draw(image) >>> categories = cppe5["train"].features["objects"].feature["category"].names >>> id2label = {index: x for index, x in enumerate(categories, start=0)} >>> label2id = {v: k for k, v in id2label.items(...
81_2_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
>>> for i in range(len(annotations["id"])): ... box = annotations["bbox"][i] ... class_idx = annotations["category"][i] ... x, y, w, h = tuple(box) ... # Check if coordinates are normalized or not ... if max(box) > 1.0: ... # Coordinates are un-normalized, no need to re-scale them ... ...
81_2_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
... else: ... # Coordinates are normalized, re-scale them ... x1 = int(x * width) ... y1 = int(y * height) ... x2 = int((x + w) * width) ... y2 = int((y + h) * height) ... draw.rectangle((x, y, x + w, y + h), outline="red", width=1) ... draw.text((x, y), id2label[clas...
81_2_9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
>>> image ``` <div class="flex justify-center"> <img src="https://i.imgur.com/oVQb9SF.png" alt="CPPE-5 Image Example"/> </div> To visualize the bounding boxes with associated labels, you can get the labels from the dataset's metadata, specifically the `category` field. You'll also want to create dictionaries that map...
81_2_10
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
You can use them later when setting up the model. Including these maps will make your model reusable by others if you share it on the Hugging Face Hub. Please note that, the part of above code that draws the bounding boxes assume that it is in `COCO` format `(x_min, y_min, width, height)`. It has to be adjusted to work...
81_2_11
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#load-the-cppe-5-dataset
.md
As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for object detection is bounding boxes that "stretch" beyond the edge of the image. Such "runaway" bounding boxes can raise errors during training and should be addressed. There are a few examples with t...
81_2_12
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model. [`AutoImageProcessor`] takes care of processing image data to create `pixel_values`, `pixel_mask`, and `labels` that a DETR model can train with. The image processor has some attributes that...
81_3_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
- `image_mean = [0.485, 0.456, 0.406 ]` - `image_std = [0.229, 0.224, 0.225]` These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial to replicate when doing inference or finetuning a pre-trained image model. Instantiate the image processor from the...
81_3_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
>>> MAX_SIZE = IMAGE_SIZE
81_3_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
>>> image_processor = AutoImageProcessor.from_pretrained( ... MODEL_NAME, ... do_resize=True, ... size={"max_height": MAX_SIZE, "max_width": MAX_SIZE}, ... do_pad=True, ... pad_size={"height": MAX_SIZE, "width": MAX_SIZE}, ... ) ``` Before passing the images to the `image_processor`, apply two pre...
81_3_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
- Augmenting images - Reformatting annotations to meet DETR expectations First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use [Albumentations](https://albumentations.ai/docs/). This library ensures that transformations af...
81_3_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
This library ensures that transformations affect the image and update the bounding boxes accordingly. The 🤗 Datasets library documentation has a detailed [guide on how to augment images for object detection](https://huggingface.co/docs/datasets/object_detection),
81_3_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
and it uses the exact same dataset as an example. Apply some geometric and color transformations to the image. For additional augmentation options, explore the [Albumentations Demo Space](https://huggingface.co/spaces/qubvel-hf/albumentations-demo). ```py >>> import albumentations as A
81_3_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
>>> train_augment_and_transform = A.Compose( ... [ ... A.Perspective(p=0.1), ... A.HorizontalFlip(p=0.5), ... A.RandomBrightnessContrast(p=0.5), ... A.HueSaturationValue(p=0.1), ... ], ... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True, min_area=...
81_3_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
>>> validation_transform = A.Compose( ... [A.NoOp()], ... bbox_params=A.BboxParams(format="coco", label_fields=["category"], clip=True), ... ) ``` The `image_processor` expects the annotations to be in the following format: `{'image_id': int, 'annotations': List[Dict]}`, where each dictionary is a COCO object...
81_3_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
```py >>> def format_image_annotations_as_coco(image_id, categories, areas, bboxes): ... """Format one set of image annotations to the COCO format
81_3_9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
... Args: ... image_id (str): image id. e.g. "0001" ... categories (List[int]): list of categories/class labels corresponding to provided bounding boxes ... areas (List[float]): list of corresponding areas to provided bounding boxes ... bboxes (List[Tuple[float]]): list of bounding b...
81_3_10
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
... Returns: ... dict: { ... "image_id": image id, ... "annotations": list of formatted annotations ... } ... """ ... annotations = [] ... for category, area, bbox in zip(categories, areas, bboxes): ... formatted_annotation = { ... "image_id": ...
81_3_11
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
... "iscrowd": 0, ... "area": area, ... "bbox": list(bbox), ... } ... annotations.append(formatted_annotation)
81_3_12
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
... return { ... "image_id": image_id, ... "annotations": annotations, ... } ``` Now you can combine the image and annotation transformations to use on a batch of examples: ```py >>> def augment_and_transform_batch(examples, transform, image_processor, return_pixel_mask=False): ... """A...
81_3_13
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
... images = [] ... annotations = [] ... for image_id, image, objects in zip(examples["image_id"], examples["image"], examples["objects"]): ... image = np.array(image.convert("RGB")) ... # apply augmentations ... output = transform(image=image, bboxes=objects["bbox"], category=objec...
81_3_14
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
... # format annotations in COCO format ... formatted_annotations = format_image_annotations_as_coco( ... image_id, output["category"], objects["area"], output["bboxes"] ... ) ... annotations.append(formatted_annotations) ... # Apply the image processor transformations: ...
81_3_15
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
... if not return_pixel_mask: ... result.pop("pixel_mask", None)
81_3_16
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
... return result ``` Apply this preprocessing function to the entire dataset using 🤗 Datasets [`~datasets.Dataset.with_transform`] method. This method applies transformations on the fly when you load an element of the dataset. At this point, you can check what an example from the dataset looks like after the ...
81_3_17
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
>>> # Make transform functions for batch and apply for dataset splits >>> train_transform_batch = partial( ... augment_and_transform_batch, transform=train_augment_and_transform, image_processor=image_processor ... ) >>> validation_transform_batch = partial( ... augment_and_transform_batch, transform=validation...
81_3_18
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
>>> cppe5["train"] = cppe5["train"].with_transform(train_transform_batch) >>> cppe5["validation"] = cppe5["validation"].with_transform(validation_transform_batch) >>> cppe5["test"] = cppe5["test"].with_transform(validation_transform_batch)
81_3_19
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
>>> cppe5["train"][15] {'pixel_values': tensor([[[ 1.9235, 1.9407, 1.9749, ..., -0.7822, -0.7479, -0.6965], [ 1.9578, 1.9749, 1.9920, ..., -0.7993, -0.7650, -0.7308], [ 2.0092, 2.0092, 2.0263, ..., -0.8507, -0.8164, -0.7822], ..., [ 0.0741, 0.0741, 0.0741, ..., 0.0741, 0.0741, 0.0741], [ 0.0741, 0.0741,...
81_3_20
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
[[ 1.6232, 1.6408, 1.6583, ..., 0.8704, 1.0105, 1.1331], [ 1.6408, 1.6583, 1.6758, ..., 0.8529, 0.9930, 1.0980], [ 1.6933, 1.6933, 1.7108, ..., 0.8179, 0.9580, 1.0630], ..., [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052], [ 0.2052, 0.2052, 0.2052, ..., 0.2052, 0.2052, 0.2052], [ 0....
81_3_21
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
[[ 1.8905, 1.9080, 1.9428, ..., -0.1487, -0.0964, -0.0615], [ 1.9254, 1.9428, 1.9603, ..., -0.1661, -0.1138, -0.0790], [ 1.9777, 1.9777, 1.9951, ..., -0.2010, -0.1138, -0.0790], ..., [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265], [ 0.4265, 0.4265, 0.4265, ..., 0.4265, 0.4265, 0.4265], [ 0....
81_3_22
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
[0.4858, 0.2600, 0.1150, 0.1000], [0.4042, 0.4517, 0.1217, 0.1300], [0.4242, 0.3217, 0.3617, 0.5567], [0.6617, 0.4033, 0.5400, 0.4533]]), 'area': tensor([ 4048., 4140., 5694., 72478., 88128.]), 'iscrowd': tensor([0, 0, 0, 0, 0]), 'orig_size': tensor([480, 480])}} ``` You have successfully augmented the individual i...
81_3_23
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
complete yet. In the final step, create a custom `collate_fn` to batch images together. Pad images (which are now `pixel_values`) to the largest image in a batch, and create a corresponding `pixel_mask` to indicate which pixels are real (1) and which are padding (0). ```py >>> import torch
81_3_24
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preprocess-the-data
.md
>>> def collate_fn(batch): ... data = {} ... data["pixel_values"] = torch.stack([x["pixel_values"] for x in batch]) ... data["labels"] = [x["labels"] for x in batch] ... if "pixel_mask" in batch[0]: ... data["pixel_mask"] = torch.stack([x["pixel_mask"] for x in batch]) ... return data ```
81_3_25
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preparing-function-to-compute-map
.md
Object detection models are commonly evaluated with a set of <a href="https://cocodataset.org/#detection-eval">COCO-style metrics</a>. We are going to use `torchmetrics` to compute `mAP` (mean average precision) and `mAR` (mean average recall) metrics and will wrap it to `compute_metrics` function in order to use in [`...
81_4_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preparing-function-to-compute-map
.md
Intermediate format of boxes used for training is `YOLO` (normalized) but we will compute metrics for boxes in `Pascal VOC` (absolute) format in order to correctly handle box areas. Let's define a function that converts bounding boxes to `Pascal VOC` format: ```py >>> from transformers.image_transforms import center_...
81_4_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/object_detection.md
https://huggingface.co/docs/transformers/en/tasks/object_detection/#preparing-function-to-compute-map
.md
>>> def convert_bbox_yolo_to_pascal(boxes, image_size): ... """ ... Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1] ... to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates. ... Args: ... boxes (torch.Tensor): Bounding boxes in YO...
81_4_2