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 contractor that complies with this section, as determined by the state agency, the requirements of this section may be waived under any of the following circumstances:\n(1) There is only one | 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 endangers the public health, welfare, or safety, or the contract is necessary for the provision of essential services, and no entity that complies with the requirements of this section capable of | 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 the agency has made a good faith attempt to change the terms or conditions of any grant, subvention, or agreement to authorize application of this section.\n(4) The contractor is providing | 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 practice, if the purchase of the same cannot practically be accomplished through the standard competitive bidding procedures and the contractor is not providing direct retail services to end | 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) If a contractor is unable to provide a certain benefit, despite taking reasonable measures to do so, the contractor shall not be deemed to discriminate in the provision of benefits.\n(e) (1) | 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 contracting agency shall enforce this section pursuant to its existing enforcement powers.\n(3) (A) If a contractor falsely certifies that it is in compliance with this section, the contract with that | 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 or agency proof that it has complied, or is in the process of complying, with this section.\n(B) The application of the remedies or penalties contained in Article 9 (commencing with Section | 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 enforcement powers.\n(f) Nothing in this section is intended to regulate the contracting practices of any local jurisdiction.\n(g) This section shall be construed so as not to conflict with | 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, paragraph, or section of this code or the application thereof to any person or circumstances, it is the intent of the state that the court or agency sever that clause, sentence, paragraph, or | 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 responsibility in the Department of General Services or any other contracting agency.\nSEC. 3.\nNo reimbursement is required by this act pursuant to Section 6 of Article XIII\u2009B of the | 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 infraction, or changes the penalty for a crime or infraction, within the meaning of Section 17556 of the Government Code, or changes the definition of a crime within the meaning of Section 6 | 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. Use the keyword `text_target` argument when tokenizing labels.
3. Truncate sequences to be no longer than the maximum length set by the `max_length` parameter.
```py | 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
>>> tokenized_billsum = billsum.map(preprocess_function, batched=True)
``` | 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.
<frameworkcontent>
<pt>
```py
>>> from transformers import DataCollatorForSeq2Seq | 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 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric):
```py
>>> import evaluate | 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)
... result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=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()}
```
Your `compute_metrics` function is ready to go now, and you'll return to it when you setup your training. | 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 AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer | 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_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [`Trainer`] will evaluate the ROUGE metric and save the training checkpoint. | 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="epoch",
... learning_rate=2e-5,
... per_device_train_batch_size=16,
... per_device_eval_batch_size=16,
... weight_decay=0.01,
... save_total_limit=3, | 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 [here](../training#train-a-tensorflow-model-with-keras)!
</Tip> | 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,
... collate_fn=data_collator,
... ) | 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 have a default task-relevant loss function, so you don't need to specify one unless you want to:
```py
>>> import tensorflow as tf | 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_metrics` function to [`~transformers.KerasMetricCallback`]:
```py
>>> from transformers.keras_callbacks import KerasMetricCallback | 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.io/api/models/model_training_apis/#fit-method) with your training and validation datasets, the number of epochs, and your callbacks to finetune the model:
```py | 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 look at the corresponding
[PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/summarization.ipynb) | 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 deficit and ask the ultra-wealthy and corporations to pay their fair share. And no one making under $400,000 per year will pay a penny more in taxes."
``` | 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 lift up American workers and create good-paying, union jobs across the country."}]
```
You can also manually replicate the results of the `pipeline` if you'd like:
<frameworkcontent>
<pt> | 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 controlling generation, check out the [Text Generation](../main_classes/text_generation) API.
```py
>>> from transformers import AutoModelForSeq2SeqLM | 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 ultra-wealthy and corporations to pay their fair share.'
```
</pt>
<tf>
Tokenize the text and return the `input_ids` as TensorFlow tensors:
```py
>>> from transformers import AutoTokenizer | 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 strategies and parameters for controlling generation, check out the [Text Generation](../main_classes/text_generation) API.
```py
>>> from transformers import TFAutoModelForSeq2SeqLM | 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 ultra-wealthy and corporations to pay their fair share.'
```
</tf>
</frameworkcontent> | 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 agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | 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 properly in your Markdown viewer.
--> | 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 a set of masks and corresponding classes, given an image.
Mask generation models are trained on large amounts of data and operate in two modes. | 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 only returns the mask over the object
that the prompt is pointing out. | 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.
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/sam.png" alt="SAM Architecture"/>
</div> | 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,
- Infer in point prompting mode,
- Infer in box prompting mode.
First, let's install `transformers`:
```bash
pip install -q transformers
``` | 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
import requests | 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="Example Image"/>
</div> | 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 enables batching over points and not the images. `pred_iou_thresh` is the IoU confidence threshold where only the masks above that certain threshold are returned.
```python | 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, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False]]), | 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 visualize them like this:
```python
import matplotlib.pyplot as plt | 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.co/datasets/huggingface/documentation-images/resolve/main/bee_segmented.png" alt="Visualized"/>
</div> | 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, _, _ = get_backend()
model = SamModel.from_pretrained("facebook/sam-vit-base").to(device)
processor = SamProcessor.from_pretrained("facebook/sam-vit-base")
``` | 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 processor's initial output. We need to pass these
since the processor resizes the image, and the output needs to be extrapolated.
```python | 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 in the `masks`output.
```python
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(1, 4, figsize=(15, 5)) | 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 == 1, 255, overlayed_image[:,:,0])
overlayed_image[:,:,1] = np.where(mask == 1, 0, overlayed_image[:,:,1])
overlayed_image[:,:,2] = np.where(mask == 1, 0, overlayed_image[:,:,2]) | 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
# bounding box around the bee
box = [2350, 1600, 2850, 2100]
inputs = processor(
image,
input_boxes=[[[box]]],
return_tensors="pt"
).to("cuda")
with torch.no_grad():
outputs = model(**inputs) | 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.patches as patches
fig, ax = plt.subplots()
ax.imshow(image) | 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="Visualized Bbox"/>
</div>
You can see the inference output below.
```python
fig, ax = plt.subplots()
ax.imshow(image)
ax.imshow(mask, cmap='viridis', alpha=0.4) | 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 agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | 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 properly in your Markdown viewer.
--> | 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 approach. OWL-ViT
is an open-vocabulary object detector. It means that it can detect objects in images based on free-text queries without
the need to fine-tune the model on labeled datasets. | 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 text encoder of CLIP and using them as input to the object classification and localization heads, | 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 detect objects based on textual descriptions without prior training on labeled datasets.
In this guide, you will learn how to use OWL-ViT:
- to detect objects based on text prompts | 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/index.html) Great Images dataset.
```py
>>> import skimage
>>> import numpy as np
>>> from PIL import Image | 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 image directly; other suitable options include a local path to an image or an image url. We also pass text descriptions for all items we want to query the image for.
```py | 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 badge',
'box': {'xmin': 129, 'ymin': 348, 'xmax': 206, 'ymax': 427}},
{'score': 0.2110239565372467,
'label': 'rocket',
'box': {'xmin': 350, 'ymin': -1, 'xmax': 468, 'ymax': 288}}, | 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, 'xmax': 327, 'ymax': 380}},
{'score': 0.10649408400058746,
'label': 'rocket',
'box': {'xmin': 358, 'ymin': 64, 'xmax': 424, 'ymax': 280}}]
```
Let's visualize the predictions:
```py | 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, ymin), f"{label}: {round(score,2)}", fill="white") | 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 transformers import AutoProcessor, AutoModelForZeroShotObjectDetection | 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-images/resolve/main/transformers/tasks/zero-sh-obj-detection_3.png" alt="Beach photo"/>
</div> | 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 = processor(text=text_queries, images=im, return_tensors="pt")
```
Pass the inputs through the model, post-process, and visualize the results. Since the image processor resized images before | 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 original image:
```py
>>> import torch | 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["labels"].tolist()
>>> boxes = results["boxes"].tolist() | 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"{text_queries[label]}: {round(score,2)}", fill="white") | 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 NumPy arrays.
```py
>>> images = [image, im]
>>> text_queries = [
... ["human face", "rocket", "nasa badge", "star-spangled banner"],
... ["hat", "book", "sunglasses", "camera"], | 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, or, in case
of several images, a list of tuples. Let's create predictions for the two examples, and visualize the second one (`image_idx = 1`).
```py
>>> with torch.no_grad(): | 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
... draw.rectangle((xmin, ymin, xmax, ymax), outline="red", width=1)
... draw.text((xmin, ymin), f"{text_queries[image_idx][label]}: {round(score,2)}", fill="white") | 77_4_3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.