vector listlengths 1.02k 1.02k | text stringlengths 2 11.8k |
|---|---|
[
0.01659026,
0.004415272,
0.035111025,
-0.007156435,
-0.034809384,
-0.050675705,
-0.017223706,
0.007205452,
-0.00021020614,
0.06424955,
-0.00821972,
0.006115773,
0.0049582254,
-0.017133215,
-0.015745666,
0.013860408,
-0.010806292,
-0.061474457,
-0.036287423,
-0.015549599,
-0.0... | images = [image, im]
text_queries = [
["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 ca... |
[
-0.005598673,
-0.040785033,
0.022587493,
-0.029305901,
-0.011931476,
-0.020867107,
-0.019769618,
0.018553482,
-0.008579688,
0.06745103,
0.009261911,
-0.007500739,
0.02540537,
-0.0056876587,
-0.01133824,
0.02027387,
0.0015164617,
-0.04828948,
-0.06018388,
-0.028905466,
-0.0161... |
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)
image_idx = 1
draw = ImageDraw.Draw(images[image_idx])
scores = results[image_idx]["scores"].tolist()
labels... |
[
0.020592565,
0.015259546,
-0.012472155,
-0.024347011,
-0.027532602,
0.015330653,
-0.04095759,
0.0075942194,
-0.009300786,
0.06758002,
-0.0115335435,
-0.026281118,
0.023763934,
-0.009499885,
-0.036520515,
-0.01201707,
0.010879359,
0.014832905,
-0.047357213,
0.0029704918,
-0.01... | Image-guided object detection
In addition to zero-shot object detection with text queries, OWL-ViT offers image-guided object detection. This means
you can use an image query to find similar objects in the target image.
Unlike text queries, only a single example image is allowed.
Let's take an image with two cats on a ... |
[
0.038586646,
-0.0032636907,
-0.009054576,
-0.02368342,
0.0026246717,
-0.024492122,
-0.024232183,
0.02329351,
0.037431356,
0.06579369,
-0.022022692,
-0.003812453,
0.031394973,
-0.04502738,
-0.03748912,
0.01950994,
0.0040435106,
-0.04008852,
-0.023510126,
-0.0096322205,
-0.0139... | Batch processing
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,
PyTo... |
[
-0.008379879,
-0.012769002,
-0.008038425,
-0.016318714,
-0.009731473,
-0.01913572,
-0.012399092,
0.014561642,
-0.0066797175,
0.04646636,
0.013828936,
-0.023446592,
0.004655884,
-0.0108838845,
-0.03972262,
0.011332044,
0.012057637,
-0.024328683,
-0.037986893,
-0.0051324987,
-0... | In the preprocessing step, instead of text queries, you now need to use query_images:
inputs = processor(images=image_target, query_images=query_image, return_tensors="pt")
For predictions, instead of passing the inputs to the model, pass them to [~OwlViTForObjectDetection.image_guided_detection]. Draw the prediction... |
[
0.015368649,
-0.023067445,
0.014797027,
-0.018349761,
-0.017799847,
-0.019377232,
-0.019435117,
0.016946033,
-0.023313459,
0.06899973,
0.016005391,
0.0075323745,
0.03218444,
-0.01049178,
-0.0043776045,
-0.0065808785,
-0.009268945,
-0.036004893,
-0.0493186,
-0.021765016,
-0.02... |
with torch.no_grad():
outputs = model.image_guided_detection(**inputs)
target_sizes = torch.tensor([image_target.size[::-1]])
results = processor.post_process_image_guided_detection(outputs=outputs, target_sizes=target_sizes)[0]
draw = ImageDraw.Draw(image_target)
scores = results["scores"].tolist()
bo... |
[
0.019200344,
-0.0074893357,
0.042006385,
-0.021063287,
0.014475376,
-0.020161863,
-0.030498197,
0.013040609,
0.032451283,
0.047144506,
0.004078946,
-0.013243429,
0.01846418,
0.015256611,
-0.019515842,
0.049157687,
0.002341826,
-0.013258453,
-0.009449935,
0.01606038,
0.0122293... | url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image_target = Image.open(requests.get(url, stream=True).raw)
query_url = "http://images.cocodataset.org/val2017/000000524280.jpg"
query_image = Image.open(requests.get(query_url, stream=True).raw)
Let's take a quick look at the images:
import matplotlib.... |
[
0.030169912,
0.0060969433,
0.030555388,
-0.010234384,
-0.026289454,
-0.028550914,
0.010176563,
0.026597835,
-0.0046032243,
0.068100736,
0.024323527,
-0.0019402285,
0.031120751,
-0.0033054557,
-0.01469948,
0.027265994,
0.02729169,
-0.025402859,
-0.04504928,
0.005329204,
-0.011... | Split the dataset's train split into a train and test set with the [~datasets.Dataset.train_test_split] method:
ds = ds.train_test_split(test_size=0.2)
train_ds = ds["train"]
test_ds = ds["test"]
Then take a look at an example:
train_ds[0]
{'image': ,
'annotation': ,
'scene_category': 368} |
[
0.016349861,
0.0030619625,
0.008967695,
0.013578822,
-0.038809102,
-0.0013282445,
0.03511438,
-0.030197786,
0.03921639,
0.042300176,
-0.0032128787,
-0.024961175,
0.020960988,
-0.024364784,
-0.016829884,
0.015622554,
-0.0057820906,
-0.020408234,
-0.041311037,
-0.025557568,
0.0... | import json
from huggingface_hub import cached_download, hf_hub_url
repo_id = "huggingface/label-files"
filename = "ade20k-id2label.json"
id2label = json.load(open(cached_download(hf_hub_url(repo_id, filename, repo_type="dataset")), "r"))
id2label = {int(k): v for k, v in id2label.items()}
label2id = {v: k for k, v in ... |
[
0.0044851988,
-0.032733593,
-0.020921642,
-0.008991292,
0.026869405,
-0.0072919303,
0.021938473,
0.015294249,
0.00095327885,
0.018107945,
-0.011240855,
-0.0007312824,
0.04086824,
-0.013727215,
-0.027412644,
0.0088868225,
0.010746369,
-0.030867083,
-0.06178988,
-0.021910613,
-... | Custom dataset
You could also create and use your own dataset if you prefer to train with the run_semantic_segmentation.py script instead of a notebook instance. The script requires:
a [~datasets.DatasetDict] with two [~datasets.Image] columns, "image" and "label" |
[
0.04902025,
0.0066418736,
0.00044962091,
-0.009107288,
-0.01536169,
-0.0003178207,
0.0070122,
-0.020587409,
0.026402906,
0.046496544,
-0.0035969673,
0.020532545,
0.064573966,
-0.045947913,
0.032341845,
0.030558791,
-0.0043136175,
-0.008784967,
-0.054451704,
-0.0041010226,
-0.... | Load SceneParse150 dataset
Start by loading a smaller subset of the SceneParse150 dataset from the 🤗 Datasets library. This'll give you a chance to experiment and make sure everything works before spending more time training on the full dataset.
from datasets import load_dataset
ds = load_dataset("scene_parse_150", s... |
[
0.05025798,
0.011322861,
-0.0013351098,
-0.0546037,
-0.009813146,
-0.047407866,
0.010455127,
0.005012394,
-0.012726754,
0.07269206,
0.026144873,
-0.018455204,
0.045968696,
-0.015534542,
-0.0059083463,
0.023576947,
0.0052663647,
-0.012275251,
-0.049580723,
-0.010963068,
0.0252... | ds = ds.train_test_split(test_size=0.2)
train_ds = ds["train"]
test_ds = ds["test"]
Then take a look at an example:
train_ds[0]
{'image': ,
'annotation': ,
'scene_category': 368}
image: a PIL image of the scene.
annotation: a PIL image of the segmentation map, which is also the model's target.
scene_category: a ca... |
[
0.009912122,
0.017291067,
0.027110687,
0.0057174372,
0.011128901,
-0.016195254,
0.029202692,
-0.0036681255,
0.0065677594,
0.030085035,
-0.027608782,
-0.0241648,
0.03142278,
-0.02460597,
-0.013235138,
0.009869428,
-0.0065179495,
-0.007428755,
-0.05621376,
-0.019198066,
0.00310... |
from datasets import Dataset, DatasetDict, Image
image_paths_train = ["path/to/image_1.jpg/jpg", "path/to/image_2.jpg/jpg", , "path/to/image_n.jpg/jpg"]
label_paths_train = ["path/to/annotation_1.png", "path/to/annotation_2.png", , "path/to/annotation_n.png"]
image_paths_validation = []
label_paths_validation = []... |
[
-0.005310689,
-0.023896337,
-0.008659422,
-0.016895402,
-0.010635493,
-0.021779118,
0.056289777,
-0.0066339504,
0.046296507,
0.038222846,
0.0009051108,
-0.010826043,
-0.0033187396,
-0.00484843,
0.007480838,
0.038956817,
0.027989626,
0.0131055815,
-0.05739073,
-0.013176155,
0.... | You'll also want to create a dictionary that maps a label id to a label class which will be useful when you set up the model later. Download the mappings from the Hub and create the id2label and label2id dictionaries: |
[
0.018959668,
-0.009225391,
0.009777896,
-0.024121234,
0.014117974,
-0.02346695,
-0.008265776,
0.012983883,
-0.026912842,
0.051179472,
0.013376453,
-0.03725051,
0.060659304,
-0.023219777,
0.01811637,
0.04463664,
-0.005503247,
-0.034575224,
-0.059961405,
-0.018974207,
0.0122787... |
As an example, take a look at this example dataset which was created with the steps shown above.
Preprocess
The next step is to load a SegFormer image processor to prepare the images and annotations for the model. Some datasets, like this one, use the zero-index as the background class. However, the background class ... |
[
0.021161636,
-0.00845021,
0.004817342,
-0.014220908,
-0.0013749647,
-0.017550435,
-0.022230553,
-0.0330786,
0.011505285,
0.031403,
0.0077857487,
-0.046367817,
0.055439156,
-0.034291964,
0.030218529,
0.037903164,
0.0017180288,
-0.043536637,
-0.016019287,
-0.016553745,
-0.01512... | from transformers import AutoImageProcessor
checkpoint = "nvidia/mit-b0"
image_processor = AutoImageProcessor.from_pretrained(checkpoint, reduce_labels=True)
It is common to apply some data augmentations to an image dataset to make a model more robust against overfitting. In this guide, you'll use the ColorJitter func... |
[
0.030792434,
-0.011146978,
0.018597698,
-0.027852891,
-0.028318562,
-0.033964813,
0.022905147,
-0.0019991072,
-0.012835031,
0.08248181,
-0.006970499,
-0.017317105,
0.016836884,
0.012041938,
-0.009473476,
0.025189841,
-0.00890594,
-0.014217489,
-0.03582749,
-0.016996957,
0.007... | an id2label dictionary mapping the class integers to their class names
py
import json
# simple example
id2label = {0: 'cat', 1: 'dog'}
with open('id2label.json', 'w') as fp:
json.dump(id2label, fp) |
[
0.012594754,
-0.02349259,
-0.0070136995,
0.0062278314,
-0.02681688,
-0.044564985,
-0.01694137,
-0.00295396,
-0.012643436,
0.06225745,
-0.01994575,
-0.025690239,
0.025022598,
-0.04092078,
0.017414281,
0.014521174,
-0.028124344,
-0.057417057,
-0.036608938,
0.0008154251,
0.01886... | from torchvision.transforms import ColorJitter
jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1) |
[
0.021962538,
0.0069448724,
0.0067604324,
-0.033993695,
0.008753803,
-0.044435833,
-0.0119673135,
-0.009910099,
-0.010229322,
0.024672387,
0.019649945,
-0.020884274,
0.04809626,
-0.036150225,
-0.0017388783,
0.069179155,
-0.053884834,
-0.0493164,
-0.06787389,
-0.02741061,
0.013... | Now create two preprocessing functions to prepare the images and annotations for the model. These functions convert the images into pixel_values and annotations to labels. For the training set, jitter is applied before providing the images to the image processor. For the test set, the image processor crops and normaliz... |
[
0.0055578747,
0.030220054,
0.015962897,
-0.03354625,
-0.011940191,
-0.07761124,
0.0045912876,
-0.016503049,
-0.033119816,
0.049352787,
0.009722726,
-0.00795302,
0.04557173,
-0.04230239,
-0.016815769,
0.025600336,
-0.004399392,
-0.076587796,
-0.062487,
-0.03058963,
-0.01049031... | def train_transforms(example_batch):
images = [jitter(x) for x in example_batch["image"]]
labels = [x for x in example_batch["annotation"]]
inputs = image_processor(images, labels)
return inputs
def val_transforms(example_batch):
images = [x for x in example_batch["image"]]
labels = [x for... |
[
-0.014633541,
0.038306676,
0.018260539,
0.009751044,
-0.01672604,
-0.038669378,
0.01626569,
-0.022278138,
-0.009548769,
0.06154736,
0.014814891,
-0.021789886,
0.028471934,
-0.058534164,
-0.0055939467,
0.013845366,
-0.026700284,
-0.017451439,
-0.06361196,
-0.013092067,
0.01943... | To apply the jitter over the entire dataset, use the 🤗 Datasets [~datasets.Dataset.set_transform] function. The transform is applied on the fly which is faster and consumes less disk space:
train_ds.set_transform(train_transforms)
test_ds.set_transform(val_transforms) |
[
0.02059931,
0.0074092657,
0.0052308994,
-0.008198835,
-0.019880237,
-0.01980974,
0.009503035,
-0.019739242,
0.008297532,
0.050109476,
0.011032826,
-0.011871744,
0.054790497,
-0.020951796,
0.022502737,
0.019132966,
0.011639103,
-0.024970142,
-0.016073383,
-0.019640546,
-0.0296... | It is common to apply some data augmentations to an image dataset to make a model more robust against overfitting.
In this guide, you'll use tf.image to randomly change the color properties of an image, but you can also use any image
library you like.
Define two separate transformation functions:
- training data transf... |
[
0.020152504,
0.022116223,
0.018021658,
-0.032617252,
-0.021879464,
-0.049162637,
0.011594305,
-0.016893564,
-0.003777724,
0.053173643,
0.0008216985,
0.0005161729,
0.04517949,
-0.022227641,
-0.004592459,
0.022617599,
0.013195921,
-0.06735142,
-0.07019255,
-0.046822887,
-0.0174... | def train_transforms(example_batch):
images = [aug_transforms(x.convert("RGB")) for x in example_batch["image"]]
labels = [x for x in example_batch["annotation"]]
inputs = image_processor(images, labels)
return inputs
def val_transforms(example_batch):
images = [transforms(x.convert("RGB")) for... |
[
-0.007689651,
0.0049204207,
0.044553537,
0.0006445034,
-0.018356822,
-0.020432891,
0.010339371,
-0.012114957,
-0.002702646,
0.04570084,
0.038953613,
-0.0029775205,
0.040292133,
-0.037041444,
-0.009806695,
-0.0037697046,
-0.014150051,
0.0077306265,
-0.06408498,
-0.026060132,
-... | To apply the preprocessing transformations over the entire dataset, use the 🤗 Datasets [~datasets.Dataset.set_transform] function.
The transform is applied on the fly which is faster and consumes less disk space:
train_ds.set_transform(train_transforms)
test_ds.set_transform(val_transforms) |
[
0.002387134,
-0.009703977,
0.0007869215,
-0.03150277,
-0.050274152,
-0.0062065483,
0.023168152,
-0.02507786,
0.016210305,
0.042043164,
0.03656571,
0.030436883,
0.039881792,
-0.04725415,
0.01773511,
-0.0041858116,
-0.016180698,
-0.026232567,
-0.06715064,
0.008638094,
0.0062731... | train_ds.set_transform(train_transforms)
test_ds.set_transform(val_transforms)
Evaluate
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load an evaluation method with the 🤗 Evaluate library. For this task, load the mean Intersection over Union (IoU) metric ... |
[
0.018882927,
0.04029059,
0.0039186017,
-0.014819678,
-0.058700126,
-0.034504734,
0.008908901,
-0.009375715,
0.018580483,
0.074690126,
-0.018619932,
-0.024852876,
0.05062623,
-0.042657528,
0.0016404213,
0.014898576,
-0.005203982,
-0.051993795,
-0.050284337,
-0.03495182,
0.0053... | import tensorflow as tf
def aug_transforms(image):
image = tf.keras.utils.img_to_array(image)
image = tf.image.random_brightness(image, 0.25)
image = tf.image.random_contrast(image, 0.5, 2.0)
image = tf.image.random_saturation(image, 0.75, 1.25)
image = tf.image.random_hue(image, 0.1)
imag... |
[
0.00901491,
-0.001319359,
-0.018002564,
-0.012742164,
-0.034478795,
-0.02364455,
0.0073114126,
0.017743632,
0.02815541,
0.03984822,
0.04976939,
0.024094272,
0.017034978,
-0.012653582,
0.006275686,
0.029272906,
0.0031361394,
-0.033606604,
-0.04382759,
0.015617668,
0.027160568,... | import evaluate
metric = evaluate.load("mean_iou")
Then create a function to [~evaluate.EvaluationModule.compute] the metrics. Your predictions need to be converted to
logits first, and then reshaped to match the size of the labels before you can call [~evaluate.EvaluationModule.compute]: |
[
0.022324873,
-0.02013698,
0.006107288,
-0.038824655,
0.019746782,
-0.031996198,
-0.013601171,
-0.00012868679,
-0.020624727,
0.034225896,
0.02813603,
-0.032442138,
0.05362429,
-0.008904865,
-0.02692363,
0.07196357,
-0.027745832,
-0.071740605,
-0.05423746,
-0.017698245,
-0.0011... | Next, create two preprocessing functions to prepare batches of images and annotations for the model. These functions apply
the image transformations and use the earlier loaded image_processor to convert the images into pixel_values and
annotations to labels. ImageProcessor also takes care of resizing and normalizing th... |
[
0.018826487,
-0.005696937,
-0.0412643,
0.015453116,
-0.039752584,
0.0114288675,
-0.03370571,
0.009385249,
0.0043916805,
0.055961557,
0.031214176,
0.008013505,
0.029086573,
-0.06237236,
0.0047451146,
0.031550113,
-0.030710269,
-0.041208312,
-0.06136455,
-0.017608713,
0.0012186... | import numpy as np
import torch
from torch import nn
def compute_metrics(eval_pred):
with torch.no_grad():
logits, labels = eval_pred
logits_tensor = torch.from_numpy(logits)
logits_tensor = nn.functional.interpolate(
logits_tensor,
size=labels.shape[-2:],
... |
[
-0.029160012,
0.003627511,
-0.012061386,
0.022751525,
-0.026725346,
-0.018721735,
-0.011144889,
0.024668474,
0.011368766,
0.03979418,
0.024752427,
-0.004299143,
0.019673213,
-0.040605735,
-0.019575266,
0.017924171,
-0.03215437,
-0.027145116,
-0.056389082,
-0.023199279,
0.0383... | pred_labels = logits_tensor.detach().cpu().numpy()
metrics = metric.compute(
predictions=pred_labels,
references=labels,
num_labels=num_labels,
ignore_index=255,
reduce_labels=False,
)
for key, value in metrics.items():
... |
[
0.011725333,
0.024418745,
0.0016110592,
0.016515164,
-0.01612504,
-0.048490714,
0.007939705,
0.024317602,
0.004793443,
0.0431446,
0.03349269,
0.0034858119,
0.010179293,
-0.03961905,
-0.02004071,
0.04048599,
-0.0034370467,
-0.016211735,
-0.033348203,
-0.026080376,
0.012910147,... |
pred_labels = tf.argmax(logits_resized, axis=-1)
metrics = metric.compute(
predictions=pred_labels,
references=labels,
num_labels=num_labels,
ignore_index=-1,
reduce_labels=image_processor.do_reduce_labels,
)
per_category_accuracy = metrics.pop("per_cat... |
[
0.01365396,
-0.0064666877,
-0.011937929,
0.017249454,
-0.035657782,
0.0022620407,
0.015600281,
0.005868677,
-0.0032704873,
0.027783357,
0.012443081,
0.005352382,
0.026104469,
-0.046236258,
0.019492922,
0.066858344,
0.005786961,
-0.01164821,
-0.08724271,
-0.037945826,
0.010927... | Your compute_metrics function is ready to go now, and you'll return to it when you setup your training.
Train
If you aren't familiar with finetuning a model with the [Trainer], take a look at the basic tutorial here!
You're ready to start training your model now! Load SegFormer with [AutoModelForSemanticSegmentation]... |
[
0.01437231,
-0.0019384897,
-0.011493508,
0.02308828,
-0.024187721,
-0.037496757,
-0.0074139996,
0.026979726,
-0.03506641,
0.020137146,
0.023478871,
0.009786479,
0.0016699582,
-0.05115298,
-0.008788303,
0.027775375,
0.010625527,
-0.023580136,
-0.04241531,
-0.022697689,
-0.0001... | def compute_metrics(eval_pred):
logits, labels = eval_pred
logits = tf.transpose(logits, perm=[0, 2, 3, 1])
logits_resized = tf.image.resize(
logits,
size=tf.shape(labels)[1:],
method="bilinear",
) |
[
0.050325267,
0.033625025,
0.0035084542,
0.043589037,
-0.035421353,
-0.029134205,
-0.0027383484,
0.021373503,
-0.0045399396,
0.027548382,
0.010806039,
0.022285702,
0.017766813,
-0.049370967,
0.007339686,
0.03311981,
-0.010328889,
-0.013774191,
-0.04614319,
-0.015114421,
-0.000... |
training_args = TrainingArguments(
output_dir="segformer-b0-scene-parse-150",
learning_rate=6e-5,
num_train_epochs=50,
per_device_train_batch_size=2,
per_device_eval_batch_size=2,
save_total_limit=3,
evaluation_strategy="steps",
save_strategy="steps",
save_steps=20,
e... |
[
0.023051495,
0.009920531,
0.0011795092,
0.005285647,
-0.02053521,
-0.009754225,
0.0073427833,
-0.01185113,
0.002030021,
0.034071095,
-0.009074538,
0.0048373435,
0.031063119,
-0.053304777,
0.023037035,
0.07982701,
0.0032755106,
0.0039262744,
-0.060448714,
-0.053594004,
-0.0130... | You're ready to start training your model now! Load SegFormer with [AutoModelForSemanticSegmentation], and pass the model the mapping between label ids and label classes:
from transformers import AutoModelForSemanticSegmentation, TrainingArguments, Trainer
model = AutoModelForSemanticSegmentation.from_pretrained(check... |
[
0.02943394,
0.0438372,
-0.027797205,
-0.011082055,
0.0066901515,
-0.018058635,
-0.012357344,
-0.0059706704,
-0.012977939,
0.025655812,
0.020541016,
0.027333463,
0.038272306,
-0.04607407,
-0.0023562154,
0.0074676005,
-0.007447141,
-0.034726046,
-0.08407359,
-0.0091520725,
0.01... | To fine-tune a model in TensorFlow, follow these steps:
1. Define the training hyperparameters, and set up an optimizer and a learning rate schedule.
2. Instantiate a pretrained model.
3. Convert a 🤗 Dataset to a tf.data.Dataset.
4. Compile your model.
5. Add callbacks to calculate metrics and upload your model to 🤗 ... |
[
0.048093777,
0.010178154,
0.004409807,
0.013026003,
-0.04225278,
-0.044577554,
-0.009851233,
0.003267398,
0.012241391,
0.02372723,
0.030425489,
0.012837116,
0.0062550968,
-0.044374138,
-0.017319571,
0.013251216,
0.008216625,
-0.035539992,
-0.07602013,
0.019048622,
0.005822834... |
Define your training hyperparameters in [TrainingArguments]. It is important you don't remove unused columns because this'll drop the image column. Without the image column, you can't create pixel_values. Set remove_unused_columns=False to prevent this behavior! The only other required parameter is output_dir which s... |
[
0.043961007,
0.03860731,
-0.011335206,
-0.025361057,
-0.020324722,
-0.013142768,
-0.0047776205,
0.029169356,
-0.028948585,
0.06319567,
0.030687155,
-0.020310923,
0.021414777,
-0.04271917,
-0.00074467063,
0.058614675,
-0.008313404,
-0.03573729,
-0.06915648,
0.014764054,
0.0207... | from transformers import create_optimizer
batch_size = 2
num_epochs = 50
num_train_steps = len(train_ds) * num_epochs
learning_rate = 6e-5
weight_decay_rate = 0.01
optimizer, lr_schedule = create_optimizer(
init_lr=learning_rate,
num_train_steps=num_train_steps,
weight_decay_rate=weight_decay_rate,
... |
[
0.030218331,
0.018064402,
-0.038848177,
0.0058584437,
-0.033797912,
-0.03132828,
0.010669374,
-0.0015808087,
0.009913222,
0.015872255,
0.00586885,
0.026721995,
0.0046097524,
-0.04897645,
0.009927097,
0.041068073,
0.015872255,
-0.0469508,
-0.079583265,
0.0069683916,
0.00525144... | Once training is completed, share your model to the Hub with the [~transformers.Trainer.push_to_hub] method so everyone can use your model:
trainer.push_to_hub()
If you are unfamiliar with fine-tuning a model with Keras, check out the basic tutorial first! |
[
-0.018534742,
-0.0059756823,
0.0041494276,
0.028612377,
0.0012161842,
-0.024257218,
0.0043583233,
0.011824761,
0.002780528,
0.050362848,
-0.023801446,
-0.0016806606,
0.03615794,
-0.02982777,
-0.049907073,
0.0052508777,
-0.008792609,
-0.06041516,
-0.035854094,
-0.012052647,
-0... | Convert your datasets to the tf.data.Dataset format using the [~datasets.Dataset.to_tf_dataset] and the [DefaultDataCollator]: |
[
0.0073354985,
0.052686058,
-0.053615313,
-0.006529439,
-0.008722344,
0.0006965028,
0.010228867,
0.00077086093,
0.040802833,
0.041901045,
-0.0077156494,
-0.00486452,
-0.0024129003,
-0.03325614,
-0.0010647736,
0.043083735,
0.024231082,
-0.04688524,
-0.065047994,
0.0055790623,
0... | To compute the accuracy from the predictions and push your model to the 🤗 Hub, use Keras callbacks.
Pass your compute_metrics function to [KerasMetricCallback],
and use the [PushToHubCallback] to upload the model: |
[
0.002691896,
0.034850594,
-0.03401751,
0.0052900705,
-0.014648357,
-0.011982495,
-0.006317538,
0.0028723972,
0.004991549,
0.04879083,
-0.03423967,
0.022979178,
0.022090556,
-0.07131182,
-0.005796862,
0.049651682,
-0.01362089,
-0.049068525,
-0.0529007,
0.010552371,
0.006890282... | from transformers.keras_callbacks import KerasMetricCallback, PushToHubCallback
metric_callback = KerasMetricCallback(
metric_fn=compute_metrics, eval_dataset=tf_eval_dataset, batch_size=batch_size, label_cols=["labels"]
)
push_to_hub_callback = PushToHubCallback(output_dir="scene_segmentation", tokenizer=image_p... |
[
0.02443722,
0.0097011365,
-0.017827967,
0.0016257205,
-0.0038258503,
-0.02866374,
0.0040137745,
0.0055348957,
-0.011991683,
-0.0072084838,
0.015459414,
-0.024876893,
0.04005265,
-0.053696644,
0.016664965,
0.050065808,
-0.00092189165,
-0.005276057,
-0.07040416,
-0.016239475,
0... | Then, load SegFormer with [TFAutoModelForSemanticSegmentation] along with the label mappings, and compile it with the
optimizer. Note that Transformers models all have a default task-relevant loss function, so you don't need to specify one unless you want to:
from transformers import TFAutoModelForSemanticSegmentation... |
[
0.024830213,
0.02563559,
-0.05580314,
0.0070095183,
-0.015179327,
0.011541476,
-0.014223794,
0.0050028986,
0.024379747,
0.027178094,
0.029457724,
0.020967128,
0.00033870238,
-0.03336176,
-0.019397324,
0.043381207,
0.019902391,
-0.036064554,
-0.053427957,
0.0004272172,
-0.0112... | Finally, you are ready to train your model! Call fit() with your training and validation datasets, the number of epochs,
and your callbacks to fine-tune the model:
model.fit(
tf_train_dataset,
validation_data=tf_eval_dataset,
callbacks=callbacks,
epochs=num_epochs,
)
Congratulations! You have fin... |
[
0.03429414,
-0.0069511477,
-0.019264998,
-0.04146251,
-0.041896958,
-0.016563281,
-0.014404625,
0.018993467,
0.012761872,
0.06315769,
0.043200295,
-0.039941948,
0.027220802,
-0.036547832,
-0.008682147,
0.0395075,
0.0023079982,
-0.040213477,
-0.03782402,
0.0119812265,
0.012320... | Congratulations! You have fine-tuned your model and shared it on the 🤗 Hub. You can now use it for inference!
Inference
Great, now that you've finetuned a model, you can use it for inference!
Load an image for inference:
image = ds[0]["image"]
image
We will now see how to infer without a pipeline. Process the image... |
[
-0.014589118,
-0.00012367312,
-0.002816472,
0.012403509,
-0.015926683,
-0.020642636,
0.005677759,
0.015650896,
-0.021456208,
0.056646597,
-0.0018736261,
0.010962523,
0.034583658,
-0.039189294,
-0.03532828,
0.0062155435,
-0.029398866,
-0.049641613,
-0.06938794,
-0.01497522,
-0... | from transformers import DefaultDataCollator
data_collator = DefaultDataCollator(return_tensors="tf")
tf_train_dataset = train_ds.to_tf_dataset(
columns=["pixel_values", "label"],
shuffle=True,
batch_size=batch_size,
collate_fn=data_collator,
)
tf_eval_dataset = test_ds.to_tf_dataset(
columns=... |
[
0.035123464,
0.0087168235,
-0.0061124503,
-0.008047941,
-0.0038069393,
-0.017704047,
-0.010524231,
0.022457385,
0.002682647,
0.07491487,
0.01736249,
-0.012986288,
0.033956476,
-0.057808552,
-0.001956838,
0.013911339,
-0.0003170967,
-0.029544696,
-0.018031374,
0.0011429713,
0.... | image = ds[0]["image"]
image
We will now see how to infer without a pipeline. Process the image with an image processor and place the pixel_values on a GPU:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # use GPU if available, otherwise use a CPU
encoding = image_processor(image, return_tenso... |
[
0.056273744,
0.020755114,
0.00062557275,
-0.00567881,
-0.014902533,
-0.04253895,
-0.013748699,
0.033864338,
0.007722348,
0.047877166,
0.03998105,
0.013178732,
0.022409406,
-0.05435532,
0.0044693695,
0.045096844,
-0.0012850306,
-0.046375792,
-0.0007050726,
0.0010382769,
0.0017... | Pass your input to the model and return the logits:
outputs = model(pixel_values=pixel_values)
logits = outputs.logits.cpu()
Next, rescale the logits to the original image size:
upsampled_logits = nn.functional.interpolate(
logits,
size=image.size[::-1],
mode="bilinear",
align_corners=False,
)
p... |
[
0.059682753,
0.01947513,
-0.016373638,
-0.010666615,
-0.000008533849,
-0.03956497,
-0.019517042,
0.019796455,
-0.015144219,
0.042973816,
-0.015395692,
0.0101566855,
0.03053991,
-0.079632886,
0.015214073,
0.042163517,
0.015116278,
-0.040850274,
-0.04283411,
-0.016024372,
-0.00... | Load an image processor to preprocess the image and return the input as TensorFlow tensors:
from transformers import AutoImageProcessor
image_processor = AutoImageProcessor.from_pretrained("MariaK/scene_segmentation")
inputs = image_processor(image, return_tensors="tf")
Pass your input to the model and return the log... |
[
0.06629531,
0.017863061,
0.0038820286,
-0.0011236038,
-0.0104571255,
-0.03266061,
-0.008465974,
0.010127654,
-0.012168942,
0.038075395,
0.028492086,
0.019052023,
0.018378755,
-0.060508076,
0.026271736,
0.06852998,
0.015714338,
-0.03521043,
-0.004218662,
-0.010908357,
-0.01621... | from transformers import TFAutoModelForSemanticSegmentation
model = TFAutoModelForSemanticSegmentation.from_pretrained("MariaK/scene_segmentation")
logits = model(**inputs).logits
Next, rescale the logits to the original image size and apply argmax on the class dimension: |
[
0.055739712,
0.007471735,
0.023665229,
0.018295808,
-0.010170651,
-0.046108842,
-0.008203283,
0.038040508,
-0.03537,
0.055569254,
0.03863711,
0.016903736,
0.026463578,
-0.04403494,
-0.010568386,
0.0501146,
0.03079605,
-0.044972457,
0.013189175,
-0.010561283,
-0.020185048,
-... | Next, rescale the logits to the original image size and apply argmax on the class dimension:
logits = tf.transpose(logits, [0, 2, 3, 1])
upsampled_logits = tf.image.resize(
logits,
# We reverse the shape of image because image.size returns width and height.
image.size[::-1],
)
pred_seg = tf.math.argmax... |
[
0.023495087,
-0.016239872,
0.0055679563,
-0.015550908,
0.003421973,
-0.048564952,
-0.014791641,
0.016985077,
0.010545371,
0.08014482,
-0.014165949,
-0.024577746,
0.058660384,
-0.025829129,
0.018573914,
0.021034501,
-0.019712815,
-0.05109584,
-0.047046416,
-0.017758405,
-0.001... | import matplotlib.pyplot as plt
import numpy as np
color_seg = np.zeros((pred_seg.shape[0], pred_seg.shape[1], 3), dtype=np.uint8)
palette = np.array(ade_palette())
for label, color in enumerate(palette):
color_seg[pred_seg == label, :] = color
color_seg = color_seg[, ::-1] # convert to BGR
img = np.array(image) ... |
[
0.017812222,
-0.028830947,
-0.023652975,
-0.014104796,
0.035845373,
-0.048880056,
-0.025434198,
0.010135017,
0.008409026,
0.045538537,
0.010604486,
-0.02627648,
-0.008167388,
-0.005333311,
-0.011488194,
-0.039159276,
-0.02954896,
-0.016942324,
-0.049487602,
-0.0049052653,
0.0... | Image captioning
[[open-in-colab]]
Image captioning is the task of predicting a caption for a given image. Common real world applications of it include
aiding visually impaired people that can help them navigate through different situations. Therefore, image captioning
helps to improve content accessibility for people ... |
[
0.009912886,
-0.0076977923,
-0.0048910906,
-0.0018848928,
0.012912204,
-0.041054893,
-0.009355673,
0.0073882295,
-0.0017034548,
0.08216482,
-0.0060295933,
-0.0097477855,
0.059381004,
0.0050011575,
0.018367387,
0.01418485,
0.006813819,
-0.059931338,
-0.022329789,
-0.013875288,
... | To visualize the results, load the dataset color palette as ade_palette() that maps each class to their RGB values. Then you can combine and plot your image and the predicted segmentation map: |
[
0.006109383,
-0.007565649,
0.019943912,
-0.009507338,
0.012024597,
-0.025117123,
-0.007690472,
0.018501515,
0.010332555,
0.03739137,
0.018501515,
-0.028875677,
0.0009361711,
-0.0025987416,
-0.0056621013,
0.00047588698,
-0.014326884,
-0.011497567,
-0.057862308,
-0.0109705385,
... | The dataset has two features, image and text.
Many image captioning datasets contain multiple captions per image. In those cases, a common strategy is to randomly sample a caption amongst the available ones during training. |
[
0.05156772,
-0.009603095,
-0.012493055,
-0.025031265,
-0.016030245,
-0.0153905405,
0.0134940045,
0.011763039,
-0.011048075,
0.0035240198,
0.001966151,
-0.020621067,
-0.0070367507,
-0.03759958,
0.015849622,
0.017204292,
0.000818916,
-0.05954521,
-0.04675112,
-0.0010517497,
0.0... | Fine-tune an image captioning model.
Use the fine-tuned model for inference.
Before you begin, make sure you have all the necessary libraries installed:
pip install transformers datasets evaluate -q
pip install jiwer -q
We encourage you to log in to your Hugging Face account so you can upload and share your model wi... |
[
0.0030335423,
-0.03095806,
0.024977855,
-0.007558516,
0.007840875,
-0.025368813,
-0.027772479,
-0.017607577,
-0.01908453,
0.030436784,
-0.019200368,
-0.024311779,
0.030755341,
-0.013502521,
0.00017692648,
0.020807639,
-0.025745291,
-0.018259173,
-0.09145515,
-0.0049376516,
-0... | Preprocess the dataset
Since the dataset has two modalities (image and text), the pre-processing pipeline will preprocess images and the captions.
To do so, load the processor class associated with the model you are about to fine-tune.
thon
from transformers import AutoProcessor
checkpoint = "microsoft/git-base"
proce... |
[
0.03423811,
-0.027135069,
0.015067066,
-0.0049721315,
0.04187209,
-0.0065577608,
-0.0020484035,
-0.02709202,
0.025484866,
0.025527913,
-0.024480395,
-0.038255997,
0.02842653,
-0.013919098,
0.0002863191,
0.01161599,
-0.005438493,
-0.022371005,
-0.031138603,
-0.020347713,
-0.01... | Load the Pokémon BLIP captions dataset
Use the 🤗 Dataset library to load a dataset that consists of {image-caption} pairs. To create your own image captioning dataset
in PyTorch, you can follow this notebook.
thon
from datasets import load_dataset
ds = load_dataset("lambdalabs/pokemon-blip-captions")
ds
bash
DatasetD... |
[
0.0018560071,
-0.034734912,
0.033184513,
-0.021556517,
0.008959521,
-0.044246018,
-0.017993579,
-0.0027877376,
-0.02474676,
0.060584843,
0.016786056,
-0.0012988322,
0.010390658,
-0.0151834795,
-0.011493827,
0.016711518,
-0.020587517,
-0.059988536,
-0.05345897,
-0.019320363,
-... | The processor will internally pre-process the image (which includes resizing, and pixel scaling) and tokenize the caption.
thon
def transforms(example_batch):
images = [x for x in example_batch["image"]]
captions = [x for x in example_batch["text"]]
inputs = processor(images=images, text=captions, padding=... |
[
0.009336705,
0.022838907,
0.018045733,
-0.019814642,
-0.01743232,
-0.022881703,
-0.010078507,
-0.014522179,
-0.019786112,
0.027774736,
0.008202606,
-0.019286823,
0.0025481575,
-0.012261113,
0.0014416971,
0.03740388,
-0.0259345,
-0.005199739,
-0.071897626,
-0.0044401065,
0.029... | With the dataset ready, you can now set up the model for fine-tuning.
Load a base model
Load the "microsoft/git-base" into a AutoModelForCausalLM object.
thon
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(checkpoint) |
[
0.02152221,
-0.00054141146,
0.02201681,
-0.0047587682,
-0.012336763,
-0.032926295,
-0.00008804561,
0.0109377485,
0.014965214,
0.062008835,
-0.027372634,
-0.0037483692,
0.038041882,
-0.009150119,
-0.006592325,
0.019642726,
-0.0008960227,
-0.045220666,
-0.07240959,
-0.0014043136,... |
Split the dataset’s train split into a train and test set with the [~datasets.Dataset.train_test_split] method:
python
ds = ds["train"].train_test_split(test_size=0.1)
train_ds = ds["train"]
test_ds = ds["test"]
Let's visualize a couple of samples from the training set.
thon
from textwrap import wrap
import matplotl... |
[
0.015987959,
-0.026671225,
-0.023952385,
-0.025031056,
0.0016789574,
-0.019696811,
-0.008976604,
0.00012733016,
-0.011931864,
0.041728277,
0.027794225,
0.01018826,
0.024543438,
-0.042496644,
0.014643315,
0.009567656,
-0.022415651,
-0.016120946,
-0.061942257,
0.0032156927,
0.0... |
Evaluate
Image captioning models are typically evaluated with the Rouge Score or Word Error Rate. For this guide, you will use the Word Error Rate (WER).
We use the 🤗 Evaluate library to do so. For potential limitations and other gotchas of the WER, refer to this guide.
thon
from evaluate import load
import torch
... |
[
0.067254044,
0.039858602,
0.001064623,
0.014168029,
-0.02668998,
-0.0142268175,
0.011206558,
-0.00061681995,
0.014785307,
0.030085016,
0.030481838,
0.033480052,
0.03133427,
-0.03609614,
-0.007153826,
0.02586694,
-0.024941022,
-0.032686405,
-0.05484967,
-0.00014547858,
-0.0103... |
Train!
Now, you are ready to start fine-tuning the model. You will use the 🤗 [Trainer] for this.
First, define the training arguments using [TrainingArguments].
thon
from transformers import TrainingArguments, Trainer
model_name = checkpoint.split("/")[1]
training_args = TrainingArguments(
output_dir=f"{model_n... |
[
0.011077793,
-0.008719392,
-0.014120653,
0.0019901341,
0.024149442,
-0.038329612,
-0.0050999513,
0.011122433,
0.007923338,
0.04508491,
0.010452854,
-0.02272101,
0.03815106,
-0.03538347,
-0.0091583375,
0.017647097,
-0.0044043344,
-0.031931423,
-0.035829857,
-0.021337215,
0.001... | Prepare image for the model.
thon
device = "cuda" if torch.cuda.is_available() else "cpu"
inputs = processor(images=image, return_tensors="pt").to(device)
pixel_values = inputs.pixel_values
Call [generate] and decode the predictions.
python
generated_ids = model.generate(pixel_values=pixel_values, max_length=50)
gene... |
[
0.039995763,
0.03775804,
-0.023666048,
-0.0046985107,
-0.02069186,
-0.010133488,
0.023935143,
0.010551291,
0.03549199,
0.033622503,
-0.025450563,
0.012923561,
0.022009,
-0.035265386,
-0.015338319,
0.025903773,
0.0035017538,
-0.043423165,
-0.062259696,
-0.008872998,
-0.0025316... |
Then pass them along with the datasets and the model to 🤗 Trainer.
python
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_ds,
eval_dataset=test_ds,
compute_metrics=compute_metrics,
)
To start training, simply call [~Trainer.train] on the [Trainer] object.
python
trainer.... |
[
-0.0047361464,
0.01933751,
0.0147767775,
-0.027673129,
0.03482997,
-0.019800602,
-0.004522143,
-0.04459696,
0.03982573,
0.023533385,
0.014096175,
-0.00202251,
0.031939168,
-0.039096013,
0.01479081,
0.06926702,
-0.053942956,
-0.016895764,
-0.06124013,
-0.008104073,
0.008581196... | Before you begin, make sure you have all the necessary libraries installed: |
[
-0.02083352,
-0.006789928,
0.01118504,
-0.0100291595,
0.026772112,
-0.016085416,
0.034634862,
-0.00057101843,
0.028710114,
0.03815095,
0.027215084,
0.0069802674,
0.0299006,
-0.003095612,
-0.022397764,
-0.009973788,
0.00699411,
-0.040199697,
-0.0014318719,
-0.0022460057,
-0.03... | a drawing of a pink and blue pokemon
Looks like the fine-tuned model generated a pretty good caption! |
[
0.03549216,
-0.0006737705,
-0.011255266,
-0.022781925,
-0.02569186,
-0.025767246,
0.0067132046,
-0.016223263,
-0.0051941583,
0.0030607085,
-0.04037723,
-0.006238267,
0.012220218,
-0.030727705,
0.021696353,
0.010071691,
0.017987316,
-0.031089563,
-0.051293254,
-0.019223662,
0.... | pip install -q datasets transformers evaluate timm albumentations
You'll use 🤗 Datasets to load a dataset from the Hugging Face Hub, 🤗 Transformers to train your model,
and albumentations to augment the data. timm is currently required to load a convolutional backbone for the DETR model.
We encourage you to share you... |
[
0.024960566,
-0.007100974,
0.010865776,
0.05920812,
0.021845855,
0.016902318,
-0.022517374,
-0.015444976,
0.002059211,
0.007851077,
-0.0154164005,
-0.037062228,
0.03734798,
-0.00071125827,
-0.058636617,
0.0070866863,
-0.013830469,
-0.037576582,
-0.04054842,
0.019759854,
-0.01... | from huggingface_hub import notebook_login
notebook_login()
Load the CPPE-5 dataset
The CPPE-5 dataset contains images with
annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.
Start by loading the dataset: |
[
0.023647498,
0.007382937,
0.020083798,
0.0111745475,
-0.015511764,
0.011685621,
-0.0028437083,
-0.024655832,
-0.0029075923,
0.059063494,
0.0030353607,
-0.03406234,
0.04574796,
-0.029172614,
0.001026463,
0.0016773908,
-0.0065990607,
-0.030029006,
-0.05489203,
-0.0005909285,
0.... | from datasets import load_dataset
cppe5 = load_dataset("cppe-5")
cppe5
DatasetDict({
train: Dataset({
features: ['image_id', 'image', 'width', 'height', 'objects'],
num_rows: 1000
})
test: Dataset({
features: ['image_id', 'image', 'width', 'height', 'objects'],
num_rows: 29
... |
[
0.027242959,
0.019062884,
0.025359673,
0.00051439955,
-0.010746233,
-0.020687398,
0.0038025132,
0.012694213,
0.014836271,
0.055866037,
0.027789256,
-0.0011572867,
0.045572653,
-0.013333955,
-0.014045578,
-0.0033838055,
-0.010365264,
-0.011328471,
-0.08194452,
-0.022714445,
0.... | You'll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images.
To get familiar with the data, explore what the examples look like.
cppe5["train"][0]
{'image_id': 15,
'image': ,
'width': 943,
'height': 663,
'objects': {'id': [114, 115, 116, 117],
'area': [3796... |
[
0.0023988595,
-0.010136562,
-0.008467459,
-0.020684686,
-0.0010784388,
-0.025867289,
0.04478379,
0.015822183,
0.007324238,
0.028138489,
-0.0047862865,
-0.008482702,
0.0045538316,
-0.0028218513,
-0.00898572,
0.011081626,
0.033443034,
-0.020989543,
-0.07682447,
0.0136424415,
-0... |
To visualize the bounding boxes with associated labels, you can get the labels from the dataset's metadata, specifically
the category field.
You'll also want to create dictionaries that map a label id to a label class (id2label) and the other way around (label2id).
You can use them later when setting up the model. In... |
[
0.018651515,
-0.0054999944,
-0.0071852393,
-0.06755667,
-0.014737635,
-0.035217587,
-0.0059846397,
-0.0075707533,
-0.0059222234,
0.06661675,
0.037802365,
0.0042700223,
0.024746303,
0.017447244,
-0.011477292,
0.008018684,
0.0033282675,
-0.0022543368,
-0.047230925,
-0.0068180836,... |
The examples in the dataset have the following fields:
- image_id: the example image id
- image: a PIL.Image.Image object containing the image
- width: width of the image
- height: height of the image
- objects: a dictionary containing bounding box metadata for the objects in the image:
- id: the annotation id
- ... |
[
0.039927825,
0.023922883,
0.010327133,
-0.03984329,
-0.034799483,
-0.039307915,
0.010073534,
0.006269542,
-0.05026905,
0.038124453,
0.022063153,
-0.019978002,
0.063737996,
-0.024909101,
-0.0094536245,
0.035701167,
-0.028163629,
-0.036884632,
-0.046155103,
-0.008178582,
0.0167... | image_mean = [0.485, 0.456, 0.406 ]
image_std = [0.229, 0.224, 0.225]
These are the mean and standard deviation used to normalize images during the model pre-training. These values are crucial
to replicate when doing inference or finetuning a pre-trained image model.
Instantiate the image processor from the same check... |
[
0.012217285,
-0.0025129805,
0.012854583,
-0.04571162,
-0.005996391,
-0.04078705,
-0.003566694,
-0.014737507,
-0.008509371,
0.06123851,
0.023203427,
-0.0215957,
0.048637398,
-0.012159349,
-0.002766451,
0.023898661,
-0.006970443,
-0.048492555,
-0.06691625,
-0.011717586,
0.00561... |
import numpy as np
import os
from PIL import Image, ImageDraw
image = cppe5["train"][0]["image"]
annotations = cppe5["train"][0]["objects"]
draw = ImageDraw.Draw(image)
categories = cppe5["train"].features["objects"].feature["category"].names
id2label = {index: x for index, x in enumerate(categories, start=0)}
label2... |
[
-0.0072012017,
-0.0025789328,
0.040441185,
0.02597275,
-0.035011854,
-0.06256938,
-0.008070629,
-0.020103203,
-0.0106458925,
0.07953238,
0.022568412,
0.02396243,
0.022891238,
-0.038768366,
-0.048922684,
-0.012582844,
-0.011423608,
-0.05159333,
-0.09344321,
0.00835677,
0.01289... | remove_idx = [590, 821, 822, 875, 876, 878, 879]
keep = [i for i in range(len(cppe5["train"])) if i not in remove_idx]
cppe5["train"] = cppe5["train"].select(keep) |
[
0.026264831,
-0.027745374,
-0.004548968,
-0.026042748,
0.001093751,
-0.018314315,
0.005189303,
-0.0005339208,
0.033016104,
0.064966224,
0.060761478,
-0.022178533,
0.045719165,
-0.029048251,
0.002901864,
0.04154403,
-0.011459402,
-0.019750442,
-0.033371437,
-0.0039012304,
-0.0... | import albumentations
import numpy as np
import torch
transform = albumentations.Compose(
[
albumentations.Resize(480, 480),
albumentations.HorizontalFlip(p=1.0),
albumentations.RandomBrightnessContrast(p=1.0),
],
bbox_params=albumentations.BboxParams(format="coco", label_field... |
[
0.029230507,
-0.010011851,
0.019028373,
-0.057904802,
-0.004164286,
-0.032816622,
-0.013341816,
-0.010253365,
-0.017798847,
0.041423302,
0.0062061767,
-0.030152652,
0.041481853,
0.01389803,
0.011914688,
0.037910372,
0.009192168,
-0.025834674,
-0.06147628,
-0.029742809,
-0.032... |
Before passing the images to the image_processor, apply two preprocessing transformations to the dataset:
- Augmenting images
- Reformatting annotations to meet DETR expectations
First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. H... |
[
0.017587416,
-0.007077424,
0.0136870975,
-0.054834742,
-0.03281449,
-0.03200852,
-0.013176169,
0.003907515,
-0.04769615,
0.039895512,
0.023099674,
-0.007368868,
0.015111937,
-0.026812894,
0.016162576,
0.03508848,
0.002554637,
-0.0322388,
-0.069255844,
-0.010391256,
0.01839338... | Preprocess the data
To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.
[AutoImageProcessor] takes care of processing image data to create pixel_values, pixel_mask, and
labels that a DETR model can train with. The image processor has some att... |
[
0.013388528,
0.009982234,
0.018630633,
-0.053726215,
0.011882586,
-0.06540084,
0.022388313,
0.003472627,
0.014091299,
0.051230658,
0.03453623,
-0.013919191,
0.012822007,
-0.023076743,
-0.03401991,
-0.010864284,
0.001894975,
-0.04529295,
-0.024510972,
-0.009164723,
-0.01169613... | def formatted_anns(image_id, category, area, bbox):
annotations = []
for i in range(0, len(category)):
new_ann = {
"image_id": image_id,
"category_id": category[i],
"isCrowd": 0,
"area": area[i],
"bbox": list(bbox[i]),
}
... |
[
0.010488381,
0.01326346,
0.016323164,
-0.047418296,
-0.0022004964,
-0.06557728,
-0.0065997103,
0.0039313636,
0.0055216984,
0.0617064,
-0.005044954,
-0.020791756,
-0.007805803,
-0.022015637,
-0.024278395,
-0.007592335,
-0.0060375785,
-0.04326279,
-0.045625165,
-0.0047034053,
0... | area.append(objects["area"])
images.append(out["image"])
bboxes.append(out["bboxes"])
categories.append(out["category"])
targets = [
{"image_id": id_, "annotations": formatted_anns(id_, cat_, ar_, box_)}
for id_, cat_, ar_, box_ in zip(image_ids, categories, area, bboxe... |
[
-0.013091646,
-0.0014099382,
0.016665986,
-0.011572016,
-0.0060464144,
-0.043120388,
0.005778874,
-0.007016694,
-0.007048799,
0.04195034,
0.03809776,
0.0010220045,
0.05787435,
-0.029422315,
-0.024199925,
0.010637408,
-0.020432957,
-0.017165394,
-0.05085409,
-0.013755146,
-0.0... | Apply this preprocessing function to the entire dataset using 🤗 Datasets [~datasets.Dataset.with_transform] method. This method applies
transformations on the fly when you load an element of the dataset.
At this point, you can check what an example from the dataset looks like after the transformations. You should see ... |
[
0.021357145,
0.049564134,
0.022613449,
0.016960086,
-0.050072636,
-0.01348282,
0.012667719,
-0.03691137,
-0.013176222,
0.04890607,
0.018425774,
0.012802322,
0.05114947,
-0.070711896,
-0.0017648062,
-0.011000127,
0.015389708,
-0.04618408,
-0.0702333,
-0.0022920046,
0.002731336... |
cppe5["train"] = cppe5["train"].with_transform(transform_aug_ann)
cppe5["train"][15]
{'pixel_values': tensor([[[ 0.9132, 0.9132, 0.9132, , -1.9809, -1.9809, -1.9809],
[ 0.9132, 0.9132, 0.9132, , -1.9809, -1.9809, -1.9809],
[ 0.9132, 0.9132, 0.9132, , -1.9638, -1.9638, -1.9638],
... |
[
0.004094971,
-0.027372219,
0.014931617,
-0.029645996,
-0.0027028255,
-0.040696263,
0.016133677,
-0.020246752,
0.02323018,
0.044143133,
0.02825566,
0.0070096054,
0.013454387,
-0.00029101086,
-0.039885234,
0.018320559,
0.004352038,
-0.044809334,
-0.028791519,
-0.016886776,
0.01... | The image_processor expects the annotations to be in the following format: {'image_id': int, 'annotations': List[Dict]},
where each dictionary is a COCO object annotation. Let's add a function to reformat annotations for a single example: |
[
-0.0027325887,
-0.018215125,
-0.003818269,
0.01329039,
-0.031236894,
-0.006504488,
-0.0059416615,
0.0113652665,
0.023996893,
0.062627286,
0.046919297,
0.03446036,
0.012158341,
-0.051447496,
-0.046407636,
0.035202265,
0.005020672,
-0.039832797,
-0.0076429336,
-0.029215833,
-0.... | [[ 1.3081, 1.3081, 1.3081, , -1.8431, -1.8431, -1.8431],
[ 1.3081, 1.3081, 1.3081, , -1.8431, -1.8431, -1.8431],
[ 1.3081, 1.3081, 1.3081, , -1.8256, -1.8256, -1.8256],
,
[-1.3179, -1.3179, -1.3179, , -1.8606, -1.8606, -1.8606],
[-1.3004, -1.3004, -1.3004, , -1.8606, -1.8431, -1... |
[
0.025452998,
-0.0012376948,
-0.005068485,
-0.037380524,
-0.026152099,
-0.048623215,
-0.00577472,
-0.006684265,
0.045684136,
0.061235573,
0.024411479,
-0.011849055,
0.028691692,
0.0002545835,
-0.009601943,
0.03609646,
0.007861324,
-0.08143818,
-0.055414487,
-0.028392076,
-0.01... | return annotations
Now you can combine the image and annotation transformations to use on a batch of examples:
transforming a batch
def transform_aug_ann(examples):
image_ids = examples["image_id"]
images, bboxes, area, categories = [], [], [], []
for image, objects in zip(examples["image"], examples["... |
[
0.039910316,
-0.026625842,
0.027009869,
-0.0118906,
-0.0015538853,
-0.04727794,
-0.013860514,
-0.015631303,
0.002202819,
0.021121461,
0.039056927,
-0.012082614,
0.048330456,
-0.016669597,
-0.03476152,
0.049212296,
-0.012608873,
-0.058997862,
-0.0155744115,
-0.014230318,
-0.02... | You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn't
complete yet. In the final step, create a custom collate_fn to batch images together.
Pad images (which are now pixel_values) to the largest image in a batch, and create a corresponding pixel_mask
to indic... |
[
-0.0018330142,
0.0018378338,
0.00089562265,
0.0057898187,
-0.029739492,
-0.00961971,
0.011084836,
0.0136231035,
0.025626857,
0.07145703,
0.047835086,
-0.0013245576,
0.018352633,
-0.048015013,
-0.020498915,
0.02286368,
-0.011116967,
-0.06796129,
-0.007826858,
-0.03230989,
0.00... | [[ 1.4200, 1.4200, 1.4200, , -1.6476, -1.6476, -1.6476],
[ 1.4200, 1.4200, 1.4200, , -1.6476, -1.6476, -1.6476],
[ 1.4200, 1.4200, 1.4200, , -1.6302, -1.6302, -1.6302],
,
[-1.0201, -1.0201, -1.0201, , -1.5604, -1.5604, -1.5604],
[-1.0027, -1.0027, -1.0027, , -1.5604, -1.5430, -1... |
[
0.009403085,
-0.012607254,
0.026080124,
0.024502471,
0.002834189,
-0.06841146,
0.011413544,
-0.022827089,
-0.0069947224,
0.02934712,
0.012816678,
-0.014052272,
0.022422204,
-0.039008494,
-0.015204098,
0.02064909,
-0.021961475,
-0.06913746,
-0.026540853,
-0.013221562,
-0.00403... | def collate_fn(batch):
pixel_values = [item["pixel_values"] for item in batch]
encoding = image_processor.pad(pixel_values, return_tensors="pt")
labels = [item["labels"] for item in batch]
batch = {}
batch["pixel_values"] = encoding["pixel_values"]
batch["pixel_mask"] = encoding["pixel_mas... |
[
0.023792246,
0.0054009436,
-0.0027134104,
-0.023481721,
-0.039717823,
-0.04373988,
-0.019356154,
-0.0054711816,
-0.027281974,
0.04524815,
0.02314162,
-0.004805768,
0.016162166,
-0.008435971,
0.0116373515,
0.03956995,
0.007034905,
-0.014128957,
-0.07411233,
-0.026971448,
0.008... |
Training the DETR model
You have done most of the heavy lifting in the previous sections, so now you are ready to train your model!
The images in this dataset are still quite large, even after resizing. This means that finetuning this model will
require at least one GPU.
Training involves the following steps:
1. Load... |
[
-0.004157326,
-0.0277248,
0.011137313,
-0.01400179,
-0.03933604,
-0.015583875,
0.010670355,
-0.003620672,
0.009137057,
0.06991835,
0.030526552,
-0.042151734,
0.023473386,
-0.022344321,
0.00091649353,
0.0650118,
0.013966943,
-0.017382015,
-0.057205923,
-0.047978263,
0.01166002... | from transformers import AutoModelForObjectDetection
model = AutoModelForObjectDetection.from_pretrained(
checkpoint,
id2label=id2label,
label2id=label2id,
ignore_mismatched_sizes=True,
) |
[
0.018799994,
0.0015422421,
-0.005579262,
-0.0016570055,
-0.025000744,
-0.059549794,
0.03647001,
-0.012514496,
-0.019590978,
0.05825032,
0.04002944,
0.030820126,
0.026342591,
-0.030904874,
-0.018023135,
0.018672872,
0.00599241,
-0.02271254,
-0.01366566,
-0.0073872255,
0.006426... | 'pixel_mask': tensor([[1, 1, 1, , 1, 1, 1],
[1, 1, 1, , 1, 1, 1],
[1, 1, 1, , 1, 1, 1],
,
[1, 1, 1, , 1, 1, 1],
[1, 1, 1, , 1, 1, 1],
[1, 1, 1, , 1, 1, 1]]),
'labels': {'size': tensor([800, 800]), 'image_id': tensor([756]), 'class_labels': tensor([4]), 'boxes... |
[
0.040839992,
0.002096383,
0.00037717348,
0.007550487,
-0.027661728,
-0.030735252,
-0.0027068774,
0.013206335,
0.008224136,
0.036377065,
0.024082964,
-0.00048506263,
0.032250963,
-0.03525432,
-0.001824467,
0.028798511,
0.010722253,
-0.019170938,
-0.060403895,
0.019648107,
0.01... | In the [TrainingArguments] use output_dir to specify where to save your model, then configure hyperparameters as you see fit.
It is important you do not remove unused columns because this will drop the image column. Without the image column, you
can't create pixel_values. For this reason, set remove_unused_columns to F... |
[
0.044809874,
0.05563101,
0.0014021073,
0.020361584,
-0.040118795,
-0.016102199,
-0.027714778,
-0.0043996847,
-0.011756476,
0.049731188,
0.033873618,
0.02892352,
0.037989102,
-0.049241934,
0.002577575,
0.013382524,
0.00573434,
-0.018016044,
-0.07361828,
-0.00037323573,
0.00085... | from transformers import TrainingArguments
training_args = TrainingArguments(
output_dir="detr-resnet-50_finetuned_cppe5",
per_device_train_batch_size=8,
num_train_epochs=10,
fp16=True,
save_steps=200,
logging_steps=50,
learning_rate=1e-5,
weight_decay=1e-4,
save_total_limit... |
[
0.045899905,
0.010662649,
-0.0054473714,
0.00752256,
-0.0064030504,
-0.032875363,
0.01963238,
0.010089242,
0.000082608654,
0.03781759,
0.013345377,
0.012157604,
0.025571244,
-0.03451367,
0.012109821,
0.022581333,
-0.0035564918,
-0.06176418,
-0.081915356,
-0.008655723,
-0.0120... | Finally, bring everything together, and call [~transformers.Trainer.train]:
from transformers import Trainer
trainer = Trainer(
model=model,
args=training_args,
data_collator=collate_fn,
train_dataset=cppe5["train"],
tokenizer=image_processor,
)
trainer.train() |
[
0.04401256,
0.016131235,
-0.011599263,
0.033382896,
-0.02812552,
-0.033928744,
-0.0013394814,
0.007627503,
0.0051675974,
0.031027133,
-0.0068302783,
0.033181794,
0.0093799615,
-0.05964104,
-0.004697163,
0.029303402,
0.005986369,
0.0014184858,
-0.058089685,
0.0050742286,
-0.00... | If you have set push_to_hub to True in the training_args, the training checkpoints are pushed to the
Hugging Face Hub. Upon training completion, push the final model to the Hub as well by calling the [~transformers.Trainer.push_to_hub] method.
trainer.push_to_hub() |
[
0.018469281,
0.017742805,
0.001982095,
-0.053563714,
-0.0123431245,
-0.03523414,
0.036631208,
-0.020215621,
0.010086855,
0.062644675,
0.004089926,
-0.020676654,
0.014739102,
-0.029254673,
-0.010233547,
0.008026174,
-0.0053752316,
-0.055016667,
-0.026432589,
-0.029338496,
-0.0... | import json
format annotations the same as for training, no need for data augmentation
def val_formatted_anns(image_id, objects):
annotations = []
for i in range(0, len(objects["id"])):
new_ann = {
"id": objects["id"][i],
"category_id": objects["category"][i],
"... |
[
0.011265159,
-0.026970493,
0.0028646302,
-0.0014206775,
-0.00086923625,
0.010326992,
-0.014853108,
0.006255636,
0.016743764,
0.031195823,
0.004049871,
-0.02218656,
0.04213871,
0.016672147,
-0.027700974,
-0.008235812,
0.042081416,
-0.026913201,
-0.04228194,
-0.018075816,
-0.00... | return annotations
Save images and annotations into the files torchvision.datasets.CocoDetection expects
def save_cppe5_annotation_file_images(cppe5):
output_json = {}
path_output_cppe5 = f"{os.getcwd()}/cppe5/" |
[
0.012290676,
-0.023401333,
0.0126389945,
-0.025576549,
0.009276653,
0.03491718,
-0.027936585,
0.014018053,
0.00049670966,
0.047940034,
0.038073372,
-0.018013056,
0.038926397,
0.012980205,
-0.011956574,
0.028903348,
0.0013204124,
-0.03403572,
-0.028391533,
-0.026557527,
0.0092... | Next, prepare an instance of a CocoDetection class that can be used with cocoevaluator.
import torchvision
class CocoDetection(torchvision.datasets.CocoDetection):
def init(self, img_folder, image_processor, ann_file):
super().init(img_folder, ann_file)
self.image_processor = image_processor |
[
0.018430889,
-0.030500287,
0.03752988,
-0.005726066,
-0.00047702086,
-0.053883843,
-0.013993822,
-0.008387579,
0.02977409,
0.040638003,
0.027958596,
-0.0007897396,
-0.0030046415,
0.012701191,
-0.02562024,
0.033405077,
0.013369293,
-0.014945141,
-0.025678337,
-0.0053448123,
0.... |
def getitem(self, idx):
# read in PIL image and target in COCO format
img, target = super(CocoDetection, self).getitem(idx)
# preprocess image and target: converting target to DETR format,
# resizing + normalization of both image and target)
image_id = self.ids[idx]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.