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/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | the maximum extent allowed by law or by the requirement of the contractor’s insurance provider, any request by an employee or applicant for employment benefits or any documentation of eligibility for benefits submitted by an employee or applicant for employment.\n(c) After taking all reasonable measures to find a contr... | 75_2_10 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | state agency, the requirements of this section may be waived under any of the following circumstances:\n(1) There is only one prospective contractor willing to enter into a specific contract with the state agency.\n(2) The contract is necessary to respond to an emergency, as determined by the state agency, that endange... | 75_2_11 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | necessary for the provision of essential services, and no entity that complies with the requirements of this section capable of responding to the emergency is immediately available.\n(3) The requirements of this section violate, or are inconsistent with, the terms or conditions of a grant, subvention, or agreement, if ... | 75_2_12 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | or conditions of any grant, subvention, or agreement to authorize application of this section.\n(4) The contractor is providing wholesale or bulk water, power, or natural gas, the conveyance or transmission of the same, or ancillary services, as required for ensuring reliable services in accordance with good utility pr... | 75_2_13 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | through the standard competitive bidding procedures and the contractor is not providing direct retail services to end users.\n(d) (1) A contractor shall not be deemed to discriminate in the provision of benefits if the contractor, in providing the benefits, pays the actual costs incurred in obtaining the benefit.\n(2) ... | 75_2_14 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | taking reasonable measures to do so, the contractor shall not be deemed to discriminate in the provision of benefits.\n(e) (1) Every contract subject to this chapter shall contain a statement by which the contractor certifies that the contractor is in compliance with this section.\n(2) The department or other contracti... | 75_2_15 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | powers.\n(3) (A) If a contractor falsely certifies that it is in compliance with this section, the contract with that contractor shall be subject to Article 9 (commencing with Section 10420), unless, within a time period specified by the department or other contracting agency, the contractor provides to the department ... | 75_2_16 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | complying, with this section.\n(B) The application of the remedies or penalties contained in Article 9 (commencing with Section 10420) to a contract subject to this chapter shall not preclude the application of any existing remedies otherwise available to the department or other contracting agency under its existing en... | 75_2_17 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | regulate the contracting practices of any local jurisdiction.\n(g) This section shall be construed so as not to conflict with applicable federal laws, rules, or regulations. In the event that a court or agency of competent jurisdiction holds that federal law, rule, or regulation invalidates any clause, sentence, paragr... | 75_2_18 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | any person or circumstances, it is the intent of the state that the court or agency sever that clause, sentence, paragraph, or section so that the remainder of this section shall remain in effect.\nSEC. 2.\nSection 10295.35 of the Public Contract Code shall not be construed to create any new enforcement authority or re... | 75_2_19 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | contracting agency.\nSEC. 3.\nNo reimbursement is required by this act pursuant to Section 6 of Article XIII\u2009B of the California Constitution because the only costs that may be incurred by a local agency or school district will be incurred because this act creates a new crime or infraction, eliminates a crime or i... | 75_2_20 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | the meaning of Section 17556 of the Government Code, or changes the definition of a crime within the meaning of Section 6 of Article XIII\u2009B of the California Constitution.', | 75_2_21 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#load-billsum-dataset | .md | 'title': 'An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.'}
```
There are two fields that you'll want to use:
- `text`: the text of the bill which'll be the input to the model.
- `summary`: a condensed version of `text` which'll be the model target. | 75_2_22 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#preprocess | .md | The next step is to load a T5 tokenizer to process `text` and `summary`:
```py
>>> from transformers import AutoTokenizer | 75_3_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#preprocess | .md | >>> checkpoint = "google-t5/t5-small"
>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
```
The preprocessing function you want to create needs to:
1. Prefix the input with a prompt so T5 knows this is a summarization task. Some models capable of multiple NLP tasks require prompting for specific tasks.
2. U... | 75_3_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#preprocess | .md | 3. Truncate sequences to be no longer than the maximum length set by the `max_length` parameter.
```py
>>> prefix = "summarize: " | 75_3_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#preprocess | .md | >>> def preprocess_function(examples):
... inputs = [prefix + doc for doc in examples["text"]]
... model_inputs = tokenizer(inputs, max_length=1024, truncation=True)
... labels = tokenizer(text_target=examples["summary"], max_length=128, truncation=True) | 75_3_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#preprocess | .md | ... model_inputs["labels"] = labels["input_ids"]
... return model_inputs
```
To apply the preprocessing function over the entire dataset, use 🤗 Datasets [`~datasets.Dataset.map`] method. You can speed up the `map` function by setting `batched=True` to process multiple elements of the dataset at once:
```py... | 75_3_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#preprocess | .md | ```py
>>> tokenized_billsum = billsum.map(preprocess_function, batched=True)
```
Now create a batch of examples using [`DataCollatorForSeq2Seq`]. It's more efficient to *dynamically pad* the sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.
<fra... | 75_3_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#preprocess | .md | >>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)
```
</pt>
<tf>
```py
>>> from transformers import DataCollatorForSeq2Seq
>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint, return_tensors="tf")
```
</tf>
</frameworkcontent> | 75_3_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#evaluate | .md | Including a metric during training is often helpful for evaluating your model's performance. You can quickly load a evaluation method with the 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [ROUGE](https://huggingface.co/spaces/evaluate-metric/rouge) metric (see the 🤗 Evalua... | 75_4_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#evaluate | .md | >>> rouge = evaluate.load("rouge")
```
Then create a function that passes your predictions and labels to [`~evaluate.EvaluationModule.compute`] to calculate the ROUGE metric:
```py
>>> import numpy as np | 75_4_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#evaluate | .md | >>> def compute_metrics(eval_pred):
... predictions, labels = eval_pred
... decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
... labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
... decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
.... | 75_4_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#evaluate | .md | ... result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)
... prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]
... result["gen_len"] = np.mean(prediction_lens)
... return {k: round(v, 4) for k, v in result.items()}
``... | 75_4_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | <frameworkcontent>
<pt>
<Tip>
If you aren't familiar with finetuning a model with the [`Trainer`], take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!
</Tip>
You're ready to start training your model now! Load T5 with [`AutoModelForSeq2SeqLM`]:
```py
>>> from transformers import Au... | 75_5_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | >>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
```
At this point, only three steps remain:
1. Define your training hyperparameters in [`Seq2SeqTrainingArguments`]. The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_... | 75_5_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | 2. Pass the training arguments to [`Seq2SeqTrainer`] along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.
3. Call [`~Trainer.train`] to finetune your model.
```py
>>> training_args = Seq2SeqTrainingArguments(
... output_dir="my_awesome_billsum_model",
... eval_strategy="epo... | 75_5_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | ... per_device_eval_batch_size=16,
... weight_decay=0.01,
... save_total_limit=3,
... num_train_epochs=4,
... predict_with_generate=True,
... fp16=True, #change to bf16=True for XPU
... push_to_hub=True,
... ) | 75_5_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | >>> trainer = Seq2SeqTrainer(
... model=model,
... args=training_args,
... train_dataset=tokenized_billsum["train"],
... eval_dataset=tokenized_billsum["test"],
... processing_class=tokenizer,
... data_collator=data_collator,
... compute_metrics=compute_metrics,
... ) | 75_5_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | >>> trainer.train()
```
Once training is completed, share your model to the Hub with the [`~transformers.Trainer.push_to_hub`] method so everyone can use your model:
```py
>>> trainer.push_to_hub()
```
</pt>
<tf>
<Tip>
If you aren't familiar with finetuning a model with Keras, take a look at the basic tutorial [h... | 75_5_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | </Tip>
To finetune a model in TensorFlow, start by setting up an optimizer function, learning rate schedule, and some training hyperparameters:
```py
>>> from transformers import create_optimizer, AdamWeightDecay | 75_5_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | >>> optimizer = AdamWeightDecay(learning_rate=2e-5, weight_decay_rate=0.01)
```
Then you can load T5 with [`TFAutoModelForSeq2SeqLM`]:
```py
>>> from transformers import TFAutoModelForSeq2SeqLM | 75_5_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | >>> model = TFAutoModelForSeq2SeqLM.from_pretrained(checkpoint)
```
Convert your datasets to the `tf.data.Dataset` format with [`~transformers.TFPreTrainedModel.prepare_tf_dataset`]:
```py
>>> tf_train_set = model.prepare_tf_dataset(
... tokenized_billsum["train"],
... shuffle=True,
... batch_size=16,
.... | 75_5_8 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | >>> tf_test_set = model.prepare_tf_dataset(
... tokenized_billsum["test"],
... shuffle=False,
... batch_size=16,
... collate_fn=data_collator,
... )
```
Configure the model for training with [`compile`](https://keras.io/api/models/model_training_apis/#compile-method). Note that Transformers models all... | 75_5_9 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | >>> model.compile(optimizer=optimizer) # No loss argument!
```
The last two things to setup before you start training is to compute the ROUGE score from the predictions, and provide a way to push your model to the Hub. Both are done by using [Keras callbacks](../main_classes/keras_callbacks).
Pass your `compute_me... | 75_5_10 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | >>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_test_set)
```
Specify where to push your model and tokenizer in the [`~transformers.PushToHubCallback`]:
```py
>>> from transformers.keras_callbacks import PushToHubCallback | 75_5_11 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | >>> push_to_hub_callback = PushToHubCallback(
... output_dir="my_awesome_billsum_model",
... tokenizer=tokenizer,
... )
```
Then bundle your callbacks together:
```py
>>> callbacks = [metric_callback, push_to_hub_callback]
```
Finally, you're ready to start training your model! Call [`fit`](https://keras.... | 75_5_12 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | ```py
>>> model.fit(x=tf_train_set, validation_data=tf_test_set, epochs=3, callbacks=callbacks)
```
Once training is completed, your model is automatically uploaded to the Hub so everyone can use it!
</tf>
</frameworkcontent>
<Tip>
For a more in-depth example of how to finetune a model for summarization, take a l... | 75_5_13 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#train | .md | [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb)
or [TensorFlow notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization-tf.ipynb).
</Tip> | 75_5_14 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | Great, now that you've finetuned a model, you can use it for inference!
Come up with some text you'd like to summarize. For T5, you need to prefix your input depending on the task you're working on. For summarization you should prefix your input as shown below:
```py | 75_6_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | ```py
>>> text = "summarize: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country. It'll lower the def... | 75_6_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | ```
The simplest way to try out your finetuned model for inference is to use it in a [`pipeline`]. Instantiate a `pipeline` for summarization with your model, and pass your text to it:
```py
>>> from transformers import pipeline | 75_6_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | >>> summarizer = pipeline("summarization", model="username/my_awesome_billsum_model")
>>> summarizer(text)
[{"summary_text": "The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will li... | 75_6_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | ```
You can also manually replicate the results of the `pipeline` if you'd like:
<frameworkcontent>
<pt>
Tokenize the text and return the `input_ids` as PyTorch tensors:
```py
>>> from transformers import AutoTokenizer | 75_6_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | >>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_billsum_model")
>>> inputs = tokenizer(text, return_tensors="pt").input_ids
```
Use the [`~generation.GenerationMixin.generate`] method to create the summarization. For more details about the different text generation strategies and parameters for con... | 75_6_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | >>> model = AutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_billsum_model")
>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)
```
Decode the generated token ids back into text:
```py
>>> tokenizer.decode(outputs[0], skip_special_tokens=True) | 75_6_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | ```
Decode the generated token ids back into text:
```py
>>> tokenizer.decode(outputs[0], skip_special_tokens=True)
'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ul... | 75_6_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | >>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_billsum_model")
>>> inputs = tokenizer(text, return_tensors="tf").input_ids
```
Use the [`~transformers.generation_tf_utils.TFGenerationMixin.generate`] method to create the summarization. For more details about the different text generation strategie... | 75_6_8 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | >>> model = TFAutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_billsum_model")
>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)
```
Decode the generated token ids back into text:
```py
>>> tokenizer.decode(outputs[0], skip_special_tokens=True) | 75_6_9 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/summarization.md | https://huggingface.co/docs/transformers/en/tasks/summarization/#inference | .md | ```
Decode the generated token ids back into text:
```py
>>> tokenizer.decode(outputs[0], skip_special_tokens=True)
'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ul... | 75_6_10 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/ | .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... | 76_0_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/ | .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 ... | 76_0_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation | .md | Mask generation is the task of generating semantically meaningful masks for an image.
This task is very similar to [image segmentation](semantic_segmentation), but many differences exist. Image segmentation models are trained on labeled datasets and are limited to the classes they have seen during training; they return... | 76_1_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation | .md | Mask generation models are trained on large amounts of data and operate in two modes.
- Prompting mode: In this mode, the model takes in an image and a prompt, where a prompt can be a 2D point location (XY coordinates) in the image within an object or a bounding box surrounding an object. In prompting mode, the model o... | 76_1_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation | .md | that the prompt is pointing out.
- Segment Everything mode: In segment everything, given an image, the model generates every mask in the image. To do so, a grid of points is generated and overlaid on the image for inference. | 76_1_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation | .md | Mask generation task is supported by [Segment Anything Model (SAM)](model_doc/sam). It's a powerful model that consists of a Vision Transformer-based image encoder, a prompt encoder, and a two-way transformer mask decoder. Images and prompts are encoded, and the decoder takes these embeddings and generates valid masks.... | 76_1_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation | .md | </div>
SAM serves as a powerful foundation model for segmentation as it has large data coverage. It is trained on
[SA-1B](https://ai.meta.com/datasets/segment-anything/), a dataset with 1 million images and 1.1 billion masks.
In this guide, you will learn how to:
- Infer in segment everything mode with batching,
- ... | 76_1_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation-pipeline | .md | The easiest way to infer mask generation models is to use the `mask-generation` pipeline.
```python
>>> from transformers import pipeline
>>> checkpoint = "facebook/sam-vit-base"
>>> mask_generator = pipeline(model=checkpoint, task="mask-generation")
```
Let's see the image.
```python
from PIL import Image
impor... | 76_2_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation-pipeline | .md | img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"
image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg" alt="Exampl... | 76_2_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation-pipeline | .md | <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg" alt="Example Image"/>
</div>
Let's segment everything. `points-per-batch` enables parallel inference of points in segment everything mode. This enables faster inference, but consumes more memory. Moreover, SAM only enable... | 76_2_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation-pipeline | .md | ```python
masks = mask_generator(image, points_per_batch=128, pred_iou_thresh=0.88)
```
The `masks` looks like the following:
```bash
{'masks': [array([[False, False, False, ..., True, True, True],
[False, False, False, ..., True, True, True],
[False, False, False, ..., True, True, True],
...,
[False, Fals... | 76_2_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation-pipeline | .md | [False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False]]),
array([[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
...,
'scores': tensor([0.9972, 0.9917,
...,
}
```
We can visuali... | 76_2_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#mask-generation-pipeline | .md | plt.imshow(image, cmap='gray')
for i, mask in enumerate(masks["masks"]):
plt.imshow(mask, cmap='viridis', alpha=0.1, vmin=0, vmax=1)
plt.axis('off')
plt.show()
```
Below is the original image in grayscale with colorful maps overlaid. Very impressive.
<div class="flex justify-center">
<img src="https://huggingface... | 76_2_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#point-prompting | .md | You can also use the model without the pipeline. To do so, initialize the model and
the processor.
```python
from transformers import SamModel, SamProcessor
import torch
from accelerate.test_utils.testing import get_backend
# automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.)
device, _, _ = ... | 76_3_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#point-prompting | .md | processor = SamProcessor.from_pretrained("facebook/sam-vit-base")
```
To do point prompting, pass the input point to the processor, then take the processor output
and pass it to the model for inference. To post-process the model output, pass the outputs and
`original_sizes` and `reshaped_input_sizes` we take from the... | 76_3_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#point-prompting | .md | since the processor resizes the image, and the output needs to be extrapolated.
```python
input_points = [[[2592, 1728]]] # point location of the bee | 76_3_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#point-prompting | .md | inputs = processor(image, input_points=input_points, return_tensors="pt").to(device)
with torch.no_grad():
outputs = model(**inputs)
masks = processor.image_processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu())
```
We can visualize the three masks i... | 76_3_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#point-prompting | .md | fig, axes = plt.subplots(1, 4, figsize=(15, 5))
axes[0].imshow(image)
axes[0].set_title('Original Image')
mask_list = [masks[0][0][0].numpy(), masks[0][0][1].numpy(), masks[0][0][2].numpy()]
for i, mask in enumerate(mask_list, start=1):
overlayed_image = np.array(image).copy()
overlayed_image[:,:,0] = np.where(mask ... | 76_3_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#point-prompting | .md | axes[i].imshow(overlayed_image)
axes[i].set_title(f'Mask {i}')
for ax in axes:
ax.axis('off')
plt.show()
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/masks.png" alt="Visualized"/>
</div> | 76_3_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#box-prompting | .md | You can also do box prompting in a similar fashion to point prompting. You can simply pass the input box in the format of a list
`[x_min, y_min, x_max, y_max]` format along with the image to the `processor`. Take the processor output and directly pass it
to the model, then post-process the output again.
```python
# b... | 76_4_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#box-prompting | .md | with torch.no_grad():
outputs = model(**inputs)
mask = processor.image_processor.post_process_masks(
outputs.pred_masks.cpu(),
inputs["original_sizes"].cpu(),
inputs["reshaped_input_sizes"].cpu()
)[0][0][0].numpy()
```
You can visualize the bounding box around the bee as shown below.
```python
import matplotlib.pa... | 76_4_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#box-prompting | .md | rectangle = patches.Rectangle((2350, 1600), 500, 500, linewidth=2, edgecolor='r', facecolor='none')
ax.add_patch(rectangle)
ax.axis("off")
plt.show()
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/bbox.png" alt="Visualiz... | 76_4_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/mask_generation.md | https://huggingface.co/docs/transformers/en/tasks/mask_generation/#box-prompting | .md | ax.axis("off")
plt.show()
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/box_inference.png" alt="Visualized Inference"/>
</div> | 76_4_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/ | .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... | 77_0_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_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 ... | 77_0_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection | .md | [[open-in-colab]]
Traditionally, models used for [object detection](object_detection) require labeled image datasets for training,
and are limited to detecting the set of classes from the training data.
Zero-shot object detection is supported by the [OWL-ViT](../model_doc/owlvit) model which uses a different approa... | 77_1_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection | .md | the need to fine-tune the model on labeled datasets.
OWL-ViT leverages multi-modal representations to perform open-vocabulary detection. It combines [CLIP](../model_doc/clip) with
lightweight object classification and localization heads. Open-vocabulary detection is achieved by embedding free-text queries with the te... | 77_1_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection | .md | which associate images with their corresponding textual descriptions, while ViT processes image patches as inputs. The authors
of OWL-ViT first trained CLIP from scratch and then fine-tuned OWL-ViT end to end on standard object detection datasets using
a bipartite matching loss.
With this approach, the model can dete... | 77_1_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection | .md | In this guide, you will learn how to use OWL-ViT:
- to detect objects based on text prompts
- for batch object detection
- for image-guided object detection
Before you begin, make sure you have all the necessary libraries installed:
```bash
pip install -q transformers
``` | 77_1_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection-pipeline | .md | The simplest way to try out inference with OWL-ViT is to use it in a [`pipeline`]. Instantiate a pipeline
for zero-shot object detection from a [checkpoint on the Hugging Face Hub](https://huggingface.co/models?other=owlvit):
```python
>>> from transformers import pipeline | 77_2_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection-pipeline | .md | >>> checkpoint = "google/owlv2-base-patch16-ensemble"
>>> detector = pipeline(model=checkpoint, task="zero-shot-object-detection")
```
Next, choose an image you'd like to detect objects in. Here we'll use the image of astronaut Eileen Collins that is
a part of the [NASA](https://www.nasa.gov/multimedia/imagegallery/i... | 77_2_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection-pipeline | .md | >>> image = skimage.data.astronaut()
>>> image = Image.fromarray(np.uint8(image)).convert("RGB") | 77_2_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection-pipeline | .md | >>> image
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_1.png" alt="Astronaut Eileen Collins"/>
</div>
Pass the image and the candidate object labels to look for to the pipeline.
Here we pass the... | 77_2_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection-pipeline | .md | ```py
>>> predictions = detector(
... image,
... candidate_labels=["human face", "rocket", "nasa badge", "star-spangled banner"],
... )
>>> predictions
[{'score': 0.3571370542049408,
'label': 'human face',
'box': {'xmin': 180, 'ymin': 71, 'xmax': 271, 'ymax': 178}},
{'score': 0.28099656105041504,
'label': 'nasa... | 77_2_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection-pipeline | .md | {'score': 0.2110239565372467,
'label': 'rocket',
'box': {'xmin': 350, 'ymin': -1, 'xmax': 468, 'ymax': 288}},
{'score': 0.13790413737297058,
'label': 'star-spangled banner',
'box': {'xmin': 1, 'ymin': 1, 'xmax': 105, 'ymax': 509}},
{'score': 0.11950037628412247,
'label': 'nasa badge',
'box': {'xmin': 277, 'ymin': 338, ... | 77_2_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection-pipeline | .md | 'label': 'rocket',
'box': {'xmin': 358, 'ymin': 64, 'xmax': 424, 'ymax': 280}}]
```
Let's visualize the predictions:
```py
>>> from PIL import ImageDraw | 77_2_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection-pipeline | .md | >>> draw = ImageDraw.Draw(image)
>>> for prediction in predictions:
... box = prediction["box"]
... label = prediction["label"]
... score = prediction["score"]
... xmin, ymin, xmax, ymax = box.values()
... draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1)
... draw.text((xmin, ym... | 77_2_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#zero-shot-object-detection-pipeline | .md | >>> image
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_2.png" alt="Visualized predictions on NASA image"/>
</div> | 77_2_8 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#text-prompted-zero-shot-object-detection-by-hand | .md | Now that you've seen how to use the zero-shot object detection pipeline, let's replicate the same
result manually.
Start by loading the model and associated processor from a [checkpoint on the Hugging Face Hub](https://huggingface.co/models?other=owlvit).
Here we'll use the same checkpoint as before:
```py
>>> from... | 77_3_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#text-prompted-zero-shot-object-detection-by-hand | .md | >>> model = AutoModelForZeroShotObjectDetection.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)
```
Let's take a different image to switch things up.
```py
>>> import requests | 77_3_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#text-prompted-zero-shot-object-detection-by-hand | .md | >>> url = "https://unsplash.com/photos/oj0zeY2Ltk4/download?ixid=MnwxMjA3fDB8MXxzZWFyY2h8MTR8fHBpY25pY3xlbnwwfHx8fDE2Nzc0OTE1NDk&force=true&w=640"
>>> im = Image.open(requests.get(url, stream=True).raw)
>>> im
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-im... | 77_3_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#text-prompted-zero-shot-object-detection-by-hand | .md | </div>
Use the processor to prepare the inputs for the model. The processor combines an image processor that prepares the
image for the model by resizing and normalizing it, and a [`CLIPTokenizer`] that takes care of the text inputs.
```py
>>> text_queries = ["hat", "book", "sunglasses", "camera"]
>>> inputs = proc... | 77_3_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#text-prompted-zero-shot-object-detection-by-hand | .md | Pass the inputs through the model, post-process, and visualize the results. Since the image processor resized images before
feeding them to the model, you need to use the [`~OwlViTImageProcessor.post_process_object_detection`] method to make sure the predicted bounding
boxes have the correct coordinates relative to the... | 77_3_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#text-prompted-zero-shot-object-detection-by-hand | .md | >>> with torch.no_grad():
... outputs = model(**inputs)
... target_sizes = torch.tensor([im.size[::-1]])
... results = processor.post_process_object_detection(outputs, threshold=0.1, target_sizes=target_sizes)[0]
>>> draw = ImageDraw.Draw(im)
>>> scores = results["scores"].tolist()
>>> labels = results["l... | 77_3_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#text-prompted-zero-shot-object-detection-by-hand | .md | >>> scores = results["scores"].tolist()
>>> labels = results["labels"].tolist()
>>> boxes = results["boxes"].tolist()
>>> for box, score, label in zip(boxes, scores, labels):
... xmin, ymin, xmax, ymax = box
... draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1)
... draw.text((xmin, ymin), f"... | 77_3_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#text-prompted-zero-shot-object-detection-by-hand | .md | >>> im
```
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_4.png" alt="Beach photo with detected objects"/>
</div> | 77_3_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#batch-processing | .md | You can pass multiple sets of images and text queries to search for different (or same) objects in several images.
Let's use both an astronaut image and the beach image together.
For batch processing, you should pass text queries as a nested list to the processor and images as lists of PIL images,
PyTorch tensors, or N... | 77_4_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#batch-processing | .md | ... ["human face", "rocket", "nasa badge", "star-spangled banner"],
... ["hat", "book", "sunglasses", "camera"],
... ]
>>> inputs = processor(text=text_queries, images=images, return_tensors="pt")
```
Previously for post-processing you passed the single image's size as a tensor, but you can also pass a tuple,... | 77_4_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#batch-processing | .md | ```py
>>> with torch.no_grad():
... outputs = model(**inputs)
... target_sizes = [x.size[::-1] for x in images]
... results = processor.post_process_object_detection(outputs, threshold=0.1, target_sizes=target_sizes) | 77_4_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/zero_shot_object_detection.md | https://huggingface.co/docs/transformers/en/tasks/zero_shot_object_detection/#batch-processing | .md | >>> image_idx = 1
>>> draw = ImageDraw.Draw(images[image_idx])
>>> scores = results[image_idx]["scores"].tolist()
>>> labels = results[image_idx]["labels"].tolist()
>>> boxes = results[image_idx]["boxes"].tolist()
>>> for box, score, label in zip(boxes, scores, labels):
... xmin, ymin, xmax, ymax = box
... dr... | 77_4_3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.