import{S as oh,i as ph,s as rh,e as l,k as c,w as u,t,M as ih,c as o,d as e,m as h,a as p,x as d,h as n,b as m,N as lh,G as a,g as i,y as g,q as f,o as j,B as b,v as ch}from"../../chunks/vendor-hf-doc-builder.js";import{T as hh}from"../../chunks/Tip-hf-doc-builder.js";import{I as me}from"../../chunks/IconCopyLink-hf-doc-builder.js";import{C as _}from"../../chunks/CodeBlock-hf-doc-builder.js";import{D as mh}from"../../chunks/DocNotebookDropdown-hf-doc-builder.js";function uh(Ct){let $,v,q,P,ls,D,zs,os,G,ms,M,S,B,Fs,U,K,Ls,Y,A;return{c(){$=t(`The task illustrated in this tutorial is supported by the following model architectures:

`),v=l("p"),q=l("a"),P=t("Conditional DETR"),ls=t(", "),D=l("a"),zs=t("Deformable DETR"),os=t(", "),G=l("a"),ms=t("DETA"),M=t(", "),S=l("a"),B=t("DETR"),Fs=t(", "),U=l("a"),K=t("Table Transformer"),Ls=t(", "),Y=l("a"),A=t("YOLOS"),this.h()},l(x){$=n(x,`The task illustrated in this tutorial is supported by the following model architectures:

`),v=o(x,"P",{});var y=p(v);q=o(y,"A",{href:!0});var W=p(q);P=n(W,"Conditional DETR"),W.forEach(e),ls=n(y,", "),D=o(y,"A",{href:!0});var qa=p(D);zs=n(qa,"Deformable DETR"),qa.forEach(e),os=n(y,", "),G=o(y,"A",{href:!0});var Ea=p(G);ms=n(Ea,"DETA"),Ea.forEach(e),M=n(y,", "),S=o(y,"A",{href:!0});var J=p(S);B=n(J,"DETR"),J.forEach(e),Fs=n(y,", "),U=o(y,"A",{href:!0});var ka=p(U);K=n(ka,"Table Transformer"),ka.forEach(e),Ls=n(y,", "),Y=o(y,"A",{href:!0});var $a=p(Y);A=n($a,"YOLOS"),$a.forEach(e),y.forEach(e),this.h()},h(){m(q,"href","../model_doc/conditional_detr"),m(D,"href","../model_doc/deformable_detr"),m(G,"href","../model_doc/deta"),m(S,"href","../model_doc/detr"),m(U,"href","../model_doc/table-transformer"),m(Y,"href","../model_doc/yolos")},m(x,y){i(x,$,y),i(x,v,y),a(v,q),a(q,P),a(v,ls),a(v,D),a(D,zs),a(v,os),a(v,G),a(G,ms),a(v,M),a(v,S),a(S,B),a(v,Fs),a(v,U),a(U,K),a(v,Ls),a(v,Y),a(Y,A)},d(x){x&&e($),x&&e(v)}}}function dh(Ct){let $,v,q,P,ls,D,zs,os,G,ms,M,S,B,Fs,U,K,Ls,Y,A,x,y,W,qa,Ea,J,ka,$a,ul,ue,dl,Ot,us,Pt,Da,gl,At,Rs,It,V,fl,de,jl,bl,ge,_l,vl,zt,Ta,wl,Ft,Hs,Lt,ps,ds,fe,Ms,yl,je,xl,Rt,gs,ql,Ss,El,kl,Ht,Ca,$l,Mt,Us,St,Oa,Dl,Ut,Pa,Tl,Yt,Ys,Nt,Aa,Cl,Gt,T,Ia,be,Ol,Pl,Al,fs,_e,Il,zl,ve,Fl,Ll,Rl,za,we,Hl,Ml,Sl,Fa,ye,Ul,Yl,Nl,Ns,xe,Gl,Bl,N,La,qe,Kl,Wl,Jl,Ra,Ee,Vl,Ql,Zl,js,ke,Xl,so,Gs,ao,eo,to,k,$e,no,lo,De,oo,po,Te,ro,io,Ce,co,ho,Oe,mo,uo,Pe,go,Bt,Q,fo,Ae,jo,bo,Ie,_o,vo,Kt,Ha,wo,Wt,Bs,Jt,Ks,Ma,Xr,Vt,I,yo,ze,xo,qo,Fe,Eo,ko,Le,$o,Do,Qt,Sa,To,Zt,Ws,Xt,rs,bs,Re,Js,Co,He,Oo,sn,C,Po,Ua,Ao,Io,Me,zo,Fo,Se,Lo,Ro,Ue,Ho,Mo,an,_s,Ye,Ne,So,Uo,Ge,Be,Yo,en,Ya,No,tn,Na,Go,nn,Vs,ln,vs,Bo,Ke,Ko,Wo,on,ws,We,Jo,Vo,Je,Qo,pn,Z,Zo,Qs,Xo,sp,Zs,ap,ep,rn,Xs,cn,X,tp,Ve,np,lp,Qe,op,pp,hn,sa,mn,Ga,rp,un,aa,dn,ys,ip,Ze,cp,hp,gn,z,mp,Xe,up,dp,st,gp,fp,at,jp,bp,fn,ea,jn,F,_p,et,vp,wp,tt,yp,xp,nt,qp,Ep,bn,ta,_n,is,xs,lt,na,kp,ot,$p,vn,Ba,Dp,wn,L,la,Tp,Ka,Cp,Op,Pp,oa,Ap,Wa,Ip,zp,Fp,pa,Lp,Ja,Rp,Hp,Mp,ra,Sp,Va,Up,Yp,yn,R,Np,pt,Gp,Bp,rt,Kp,Wp,it,Jp,Vp,xn,ia,qn,w,Qp,Qa,Zp,Xp,ct,sr,ar,ht,er,tr,mt,nr,lr,ut,or,pr,dt,rr,ir,gt,cr,hr,En,ca,kn,qs,mr,Za,ur,dr,$n,ha,Dn,O,gr,ft,fr,jr,jt,br,_r,bt,vr,wr,Xa,yr,xr,Tn,ma,Cn,cs,Es,_t,ua,qr,vt,Er,On,da,kr,Pn,ss,$r,wt,Dr,Tr,yt,Cr,Or,An,ks,Pr,xt,Ar,Ir,In,ga,zn,as,zr,qt,Fr,Lr,Et,Rr,Hr,Fn,fa,Ln,se,Mr,Rn,ja,Hn,$s,Sr,ae,Ur,Yr,Mn,hs,Ds,kt,ba,Nr,$t,Gr,Sn,_a,Un,ee,Br,Yn,va,Nn,te,Kr,Gn,wa,Bn,ya,ne,si,Kn;return D=new me({}),M=new mh({props:{classNames:"absolute z-10 right-0 top-0",options:[{label:"Mixed",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/object_detection.ipynb"},{label:"PyTorch",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/pytorch/object_detection.ipynb"},{label:"TensorFlow",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/tensorflow/object_detection.ipynb"},{label:"Mixed",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/object_detection.ipynb"},{label:"PyTorch",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/pytorch/object_detection.ipynb"},{label:"TensorFlow",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/transformers_doc/en/tensorflow/object_detection.ipynb"}]}}),us=new hh({props:{$$slots:{default:[uh]},$$scope:{ctx:Ct}}}),Rs=new _({props:{code:"pip install -q datasets transformers evaluate timm albumentations",highlighted:"pip install -q datasets transformers evaluate timm albumentations"}}),Hs=new _({props:{code:`from huggingface_hub import notebook_login

notebook_login()`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> notebook_login

<span class="hljs-meta">&gt;&gt;&gt; </span>notebook_login()`}}),Ms=new me({}),Us=new _({props:{code:`from datasets import load_dataset

cppe5 = load_dataset("cppe-5")
cppe5`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> load_dataset

<span class="hljs-meta">&gt;&gt;&gt; </span>cppe5 = load_dataset(<span class="hljs-string">&quot;cppe-5&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>cppe5
DatasetDict({
    train: Dataset({
        features: [<span class="hljs-string">&#x27;image_id&#x27;</span>, <span class="hljs-string">&#x27;image&#x27;</span>, <span class="hljs-string">&#x27;width&#x27;</span>, <span class="hljs-string">&#x27;height&#x27;</span>, <span class="hljs-string">&#x27;objects&#x27;</span>],
        num_rows: <span class="hljs-number">1000</span>
    })
    test: Dataset({
        features: [<span class="hljs-string">&#x27;image_id&#x27;</span>, <span class="hljs-string">&#x27;image&#x27;</span>, <span class="hljs-string">&#x27;width&#x27;</span>, <span class="hljs-string">&#x27;height&#x27;</span>, <span class="hljs-string">&#x27;objects&#x27;</span>],
        num_rows: <span class="hljs-number">29</span>
    })
})`}}),Ys=new _({props:{code:'cppe5["train"][0]',highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>cppe5[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">0</span>]
{<span class="hljs-string">&#x27;image_id&#x27;</span>: <span class="hljs-number">15</span>,
 <span class="hljs-string">&#x27;image&#x27;</span>: &lt;PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=943x663 at <span class="hljs-number">0x7F9EC9E77C10</span>&gt;,
 <span class="hljs-string">&#x27;width&#x27;</span>: <span class="hljs-number">943</span>,
 <span class="hljs-string">&#x27;height&#x27;</span>: <span class="hljs-number">663</span>,
 <span class="hljs-string">&#x27;objects&#x27;</span>: {<span class="hljs-string">&#x27;id&#x27;</span>: [<span class="hljs-number">114</span>, <span class="hljs-number">115</span>, <span class="hljs-number">116</span>, <span class="hljs-number">117</span>],
  <span class="hljs-string">&#x27;area&#x27;</span>: [<span class="hljs-number">3796</span>, <span class="hljs-number">1596</span>, <span class="hljs-number">152768</span>, <span class="hljs-number">81002</span>],
  <span class="hljs-string">&#x27;bbox&#x27;</span>: [[<span class="hljs-number">302.0</span>, <span class="hljs-number">109.0</span>, <span class="hljs-number">73.0</span>, <span class="hljs-number">52.0</span>],
   [<span class="hljs-number">810.0</span>, <span class="hljs-number">100.0</span>, <span class="hljs-number">57.0</span>, <span class="hljs-number">28.0</span>],
   [<span class="hljs-number">160.0</span>, <span class="hljs-number">31.0</span>, <span class="hljs-number">248.0</span>, <span class="hljs-number">616.0</span>],
   [<span class="hljs-number">741.0</span>, <span class="hljs-number">68.0</span>, <span class="hljs-number">202.0</span>, <span class="hljs-number">401.0</span>]],
  <span class="hljs-string">&#x27;category&#x27;</span>: [<span class="hljs-number">4</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>]}}`}}),Bs=new _({props:{code:`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)}
label2id = {v: k for k, v in id2label.items()}

for i in range(len(annotations["id"])):
    box = annotations["bbox"][i - 1]
    class_idx = annotations["category"][i - 1]
    x, y, w, h = tuple(box)
    draw.rectangle((x, y, x + w, y + h), outline="red", width=1)
    draw.text((x, y), id2label[class_idx], fill="white")

image`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> os
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image, ImageDraw

<span class="hljs-meta">&gt;&gt;&gt; </span>image = cppe5[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&quot;image&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>annotations = cppe5[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&quot;objects&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>draw = ImageDraw.Draw(image)

<span class="hljs-meta">&gt;&gt;&gt; </span>categories = cppe5[<span class="hljs-string">&quot;train&quot;</span>].features[<span class="hljs-string">&quot;objects&quot;</span>].feature[<span class="hljs-string">&quot;category&quot;</span>].names

<span class="hljs-meta">&gt;&gt;&gt; </span>id2label = {index: x <span class="hljs-keyword">for</span> index, x <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(categories, start=<span class="hljs-number">0</span>)}
<span class="hljs-meta">&gt;&gt;&gt; </span>label2id = {v: k <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> id2label.items()}

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(annotations[<span class="hljs-string">&quot;id&quot;</span>])):
<span class="hljs-meta">... </span>    box = annotations[<span class="hljs-string">&quot;bbox&quot;</span>][i - <span class="hljs-number">1</span>]
<span class="hljs-meta">... </span>    class_idx = annotations[<span class="hljs-string">&quot;category&quot;</span>][i - <span class="hljs-number">1</span>]
<span class="hljs-meta">... </span>    x, y, w, h = <span class="hljs-built_in">tuple</span>(box)
<span class="hljs-meta">... </span>    draw.rectangle((x, y, x + w, y + h), outline=<span class="hljs-string">&quot;red&quot;</span>, width=<span class="hljs-number">1</span>)
<span class="hljs-meta">... </span>    draw.text((x, y), id2label[class_idx], fill=<span class="hljs-string">&quot;white&quot;</span>)

<span class="hljs-meta">&gt;&gt;&gt; </span>image`}}),Ws=new _({props:{code:`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)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>remove_idx = [<span class="hljs-number">590</span>, <span class="hljs-number">821</span>, <span class="hljs-number">822</span>, <span class="hljs-number">875</span>, <span class="hljs-number">876</span>, <span class="hljs-number">878</span>, <span class="hljs-number">879</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>keep = [i <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(cppe5[<span class="hljs-string">&quot;train&quot;</span>])) <span class="hljs-keyword">if</span> i <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> remove_idx]
<span class="hljs-meta">&gt;&gt;&gt; </span>cppe5[<span class="hljs-string">&quot;train&quot;</span>] = cppe5[<span class="hljs-string">&quot;train&quot;</span>].select(keep)`}}),Js=new me({}),Vs=new _({props:{code:`from transformers import AutoImageProcessor

checkpoint = "facebook/detr-resnet-50"
image_processor = AutoImageProcessor.from_pretrained(checkpoint)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoImageProcessor

<span class="hljs-meta">&gt;&gt;&gt; </span>checkpoint = <span class="hljs-string">&quot;facebook/detr-resnet-50&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>image_processor = AutoImageProcessor.from_pretrained(checkpoint)`}}),Xs=new _({props:{code:`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_fields=["category"]),
)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> albumentations
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch

<span class="hljs-meta">&gt;&gt;&gt; </span>transform = albumentations.Compose(
<span class="hljs-meta">... </span>    [
<span class="hljs-meta">... </span>        albumentations.Resize(<span class="hljs-number">480</span>, <span class="hljs-number">480</span>),
<span class="hljs-meta">... </span>        albumentations.HorizontalFlip(p=<span class="hljs-number">1.0</span>),
<span class="hljs-meta">... </span>        albumentations.RandomBrightnessContrast(p=<span class="hljs-number">1.0</span>),
<span class="hljs-meta">... </span>    ],
<span class="hljs-meta">... </span>    bbox_params=albumentations.BboxParams(<span class="hljs-built_in">format</span>=<span class="hljs-string">&quot;coco&quot;</span>, label_fields=[<span class="hljs-string">&quot;category&quot;</span>]),
<span class="hljs-meta">... </span>)`}}),sa=new _({props:{code:`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]),
        }
        annotations.append(new_ann)

    return annotations`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">formatted_anns</span>(<span class="hljs-params">image_id, category, area, bbox</span>):
<span class="hljs-meta">... </span>    annotations = []
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">0</span>, <span class="hljs-built_in">len</span>(category)):
<span class="hljs-meta">... </span>        new_ann = {
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;image_id&quot;</span>: image_id,
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;category_id&quot;</span>: category[i],
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;isCrowd&quot;</span>: <span class="hljs-number">0</span>,
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;area&quot;</span>: area[i],
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;bbox&quot;</span>: <span class="hljs-built_in">list</span>(bbox[i]),
<span class="hljs-meta">... </span>        }
<span class="hljs-meta">... </span>        annotations.append(new_ann)

<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> annotations`}}),aa=new _({props:{code:`# 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["objects"]):
        image = np.array(image.convert("RGB"))[:, :, ::-1]
        out = transform(image=image, bboxes=objects["bbox"], category=objects["category"])

        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, bboxes)
    ]

    return image_processor(images=images, annotations=targets, return_tensors="pt")`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-comment"># transforming a batch</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">transform_aug_ann</span>(<span class="hljs-params">examples</span>):
<span class="hljs-meta">... </span>    image_ids = examples[<span class="hljs-string">&quot;image_id&quot;</span>]
<span class="hljs-meta">... </span>    images, bboxes, area, categories = [], [], [], []
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> image, objects <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(examples[<span class="hljs-string">&quot;image&quot;</span>], examples[<span class="hljs-string">&quot;objects&quot;</span>]):
<span class="hljs-meta">... </span>        image = np.array(image.convert(<span class="hljs-string">&quot;RGB&quot;</span>))[:, :, ::-<span class="hljs-number">1</span>]
<span class="hljs-meta">... </span>        out = transform(image=image, bboxes=objects[<span class="hljs-string">&quot;bbox&quot;</span>], category=objects[<span class="hljs-string">&quot;category&quot;</span>])

<span class="hljs-meta">... </span>        area.append(objects[<span class="hljs-string">&quot;area&quot;</span>])
<span class="hljs-meta">... </span>        images.append(out[<span class="hljs-string">&quot;image&quot;</span>])
<span class="hljs-meta">... </span>        bboxes.append(out[<span class="hljs-string">&quot;bboxes&quot;</span>])
<span class="hljs-meta">... </span>        categories.append(out[<span class="hljs-string">&quot;category&quot;</span>])

<span class="hljs-meta">... </span>    targets = [
<span class="hljs-meta">... </span>        {<span class="hljs-string">&quot;image_id&quot;</span>: id_, <span class="hljs-string">&quot;annotations&quot;</span>: formatted_anns(id_, cat_, ar_, box_)}
<span class="hljs-meta">... </span>        <span class="hljs-keyword">for</span> id_, cat_, ar_, box_ <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(image_ids, categories, area, bboxes)
<span class="hljs-meta">... </span>    ]

<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> image_processor(images=images, annotations=targets, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)`}}),ea=new _({props:{code:`cppe5["train"] = cppe5["train"].with_transform(transform_aug_ann)
cppe5["train"][15]

`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>cppe5[<span class="hljs-string">&quot;train&quot;</span>] = cppe5[<span class="hljs-string">&quot;train&quot;</span>].with_transform(transform_aug_ann)
<span class="hljs-meta">&gt;&gt;&gt; </span>cppe5[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">15</span>]
{<span class="hljs-string">&#x27;pixel_values&#x27;</span>: tensor([[[ <span class="hljs-number">0.9132</span>,  <span class="hljs-number">0.9132</span>,  <span class="hljs-number">0.9132</span>,  ..., -<span class="hljs-number">1.9809</span>, -<span class="hljs-number">1.9809</span>, -<span class="hljs-number">1.9809</span>],
          [ <span class="hljs-number">0.9132</span>,  <span class="hljs-number">0.9132</span>,  <span class="hljs-number">0.9132</span>,  ..., -<span class="hljs-number">1.9809</span>, -<span class="hljs-number">1.9809</span>, -<span class="hljs-number">1.9809</span>],
          [ <span class="hljs-number">0.9132</span>,  <span class="hljs-number">0.9132</span>,  <span class="hljs-number">0.9132</span>,  ..., -<span class="hljs-number">1.9638</span>, -<span class="hljs-number">1.9638</span>, -<span class="hljs-number">1.9638</span>],
          ...,
          [-<span class="hljs-number">1.5699</span>, -<span class="hljs-number">1.5699</span>, -<span class="hljs-number">1.5699</span>,  ..., -<span class="hljs-number">1.9980</span>, -<span class="hljs-number">1.9980</span>, -<span class="hljs-number">1.9980</span>],
          [-<span class="hljs-number">1.5528</span>, -<span class="hljs-number">1.5528</span>, -<span class="hljs-number">1.5528</span>,  ..., -<span class="hljs-number">1.9980</span>, -<span class="hljs-number">1.9809</span>, -<span class="hljs-number">1.9809</span>],
          [-<span class="hljs-number">1.5528</span>, -<span class="hljs-number">1.5528</span>, -<span class="hljs-number">1.5528</span>,  ..., -<span class="hljs-number">1.9980</span>, -<span class="hljs-number">1.9809</span>, -<span class="hljs-number">1.9809</span>]],

         [[ <span class="hljs-number">1.3081</span>,  <span class="hljs-number">1.3081</span>,  <span class="hljs-number">1.3081</span>,  ..., -<span class="hljs-number">1.8431</span>, -<span class="hljs-number">1.8431</span>, -<span class="hljs-number">1.8431</span>],
          [ <span class="hljs-number">1.3081</span>,  <span class="hljs-number">1.3081</span>,  <span class="hljs-number">1.3081</span>,  ..., -<span class="hljs-number">1.8431</span>, -<span class="hljs-number">1.8431</span>, -<span class="hljs-number">1.8431</span>],
          [ <span class="hljs-number">1.3081</span>,  <span class="hljs-number">1.3081</span>,  <span class="hljs-number">1.3081</span>,  ..., -<span class="hljs-number">1.8256</span>, -<span class="hljs-number">1.8256</span>, -<span class="hljs-number">1.8256</span>],
          ...,
          [-<span class="hljs-number">1.3179</span>, -<span class="hljs-number">1.3179</span>, -<span class="hljs-number">1.3179</span>,  ..., -<span class="hljs-number">1.8606</span>, -<span class="hljs-number">1.8606</span>, -<span class="hljs-number">1.8606</span>],
          [-<span class="hljs-number">1.3004</span>, -<span class="hljs-number">1.3004</span>, -<span class="hljs-number">1.3004</span>,  ..., -<span class="hljs-number">1.8606</span>, -<span class="hljs-number">1.8431</span>, -<span class="hljs-number">1.8431</span>],
          [-<span class="hljs-number">1.3004</span>, -<span class="hljs-number">1.3004</span>, -<span class="hljs-number">1.3004</span>,  ..., -<span class="hljs-number">1.8606</span>, -<span class="hljs-number">1.8431</span>, -<span class="hljs-number">1.8431</span>]],

         [[ <span class="hljs-number">1.4200</span>,  <span class="hljs-number">1.4200</span>,  <span class="hljs-number">1.4200</span>,  ..., -<span class="hljs-number">1.6476</span>, -<span class="hljs-number">1.6476</span>, -<span class="hljs-number">1.6476</span>],
          [ <span class="hljs-number">1.4200</span>,  <span class="hljs-number">1.4200</span>,  <span class="hljs-number">1.4200</span>,  ..., -<span class="hljs-number">1.6476</span>, -<span class="hljs-number">1.6476</span>, -<span class="hljs-number">1.6476</span>],
          [ <span class="hljs-number">1.4200</span>,  <span class="hljs-number">1.4200</span>,  <span class="hljs-number">1.4200</span>,  ..., -<span class="hljs-number">1.6302</span>, -<span class="hljs-number">1.6302</span>, -<span class="hljs-number">1.6302</span>],
          ...,
          [-<span class="hljs-number">1.0201</span>, -<span class="hljs-number">1.0201</span>, -<span class="hljs-number">1.0201</span>,  ..., -<span class="hljs-number">1.5604</span>, -<span class="hljs-number">1.5604</span>, -<span class="hljs-number">1.5604</span>],
          [-<span class="hljs-number">1.0027</span>, -<span class="hljs-number">1.0027</span>, -<span class="hljs-number">1.0027</span>,  ..., -<span class="hljs-number">1.5604</span>, -<span class="hljs-number">1.5430</span>, -<span class="hljs-number">1.5430</span>],
          [-<span class="hljs-number">1.0027</span>, -<span class="hljs-number">1.0027</span>, -<span class="hljs-number">1.0027</span>,  ..., -<span class="hljs-number">1.5604</span>, -<span class="hljs-number">1.5430</span>, -<span class="hljs-number">1.5430</span>]]]),
 <span class="hljs-string">&#x27;pixel_mask&#x27;</span>: tensor([[<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>,  ..., <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>],
         [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>,  ..., <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>],
         [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>,  ..., <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>],
         ...,
         [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>,  ..., <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>],
         [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>,  ..., <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>],
         [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>,  ..., <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>]]),
 <span class="hljs-string">&#x27;labels&#x27;</span>: {<span class="hljs-string">&#x27;size&#x27;</span>: tensor([<span class="hljs-number">800</span>, <span class="hljs-number">800</span>]), <span class="hljs-string">&#x27;image_id&#x27;</span>: tensor([<span class="hljs-number">756</span>]), <span class="hljs-string">&#x27;class_labels&#x27;</span>: tensor([<span class="hljs-number">4</span>]), <span class="hljs-string">&#x27;boxes&#x27;</span>: tensor([[<span class="hljs-number">0.7340</span>, <span class="hljs-number">0.6986</span>, <span class="hljs-number">0.3414</span>, <span class="hljs-number">0.5944</span>]]), <span class="hljs-string">&#x27;area&#x27;</span>: tensor([<span class="hljs-number">519544.4375</span>]), <span class="hljs-string">&#x27;iscrowd&#x27;</span>: tensor([<span class="hljs-number">0</span>]), <span class="hljs-string">&#x27;orig_size&#x27;</span>: tensor([<span class="hljs-number">480</span>, <span class="hljs-number">480</span>])}}`}}),ta=new _({props:{code:`def collate_fn(batch):
    pixel_values = [item["pixel_values"] for item in batch]
    encoding = image_processor.pad_and_create_pixel_mask(pixel_values, return_tensors="pt")
    labels = [item["labels"] for item in batch]
    batch = {}
    batch["pixel_values"] = encoding["pixel_values"]
    batch["pixel_mask"] = encoding["pixel_mask"]
    batch["labels"] = labels
    return batch`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">collate_fn</span>(<span class="hljs-params">batch</span>):
<span class="hljs-meta">... </span>    pixel_values = [item[<span class="hljs-string">&quot;pixel_values&quot;</span>] <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> batch]
<span class="hljs-meta">... </span>    encoding = image_processor.pad_and_create_pixel_mask(pixel_values, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
<span class="hljs-meta">... </span>    labels = [item[<span class="hljs-string">&quot;labels&quot;</span>] <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> batch]
<span class="hljs-meta">... </span>    batch = {}
<span class="hljs-meta">... </span>    batch[<span class="hljs-string">&quot;pixel_values&quot;</span>] = encoding[<span class="hljs-string">&quot;pixel_values&quot;</span>]
<span class="hljs-meta">... </span>    batch[<span class="hljs-string">&quot;pixel_mask&quot;</span>] = encoding[<span class="hljs-string">&quot;pixel_mask&quot;</span>]
<span class="hljs-meta">... </span>    batch[<span class="hljs-string">&quot;labels&quot;</span>] = labels
<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> batch`}}),na=new me({}),ia=new _({props:{code:`from transformers import AutoModelForObjectDetection

model = AutoModelForObjectDetection.from_pretrained(
    checkpoint,
    id2label=id2label,
    label2id=label2id,
    ignore_mismatched_sizes=True,
)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForObjectDetection

<span class="hljs-meta">&gt;&gt;&gt; </span>model = AutoModelForObjectDetection.from_pretrained(
<span class="hljs-meta">... </span>    checkpoint,
<span class="hljs-meta">... </span>    id2label=id2label,
<span class="hljs-meta">... </span>    label2id=label2id,
<span class="hljs-meta">... </span>    ignore_mismatched_sizes=<span class="hljs-literal">True</span>,
<span class="hljs-meta">... </span>)`}}),ca=new _({props:{code:`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=2,
    remove_unused_columns=False,
    push_to_hub=True,
)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TrainingArguments

<span class="hljs-meta">&gt;&gt;&gt; </span>training_args = TrainingArguments(
<span class="hljs-meta">... </span>    output_dir=<span class="hljs-string">&quot;detr-resnet-50_finetuned_cppe5&quot;</span>,
<span class="hljs-meta">... </span>    per_device_train_batch_size=<span class="hljs-number">8</span>,
<span class="hljs-meta">... </span>    num_train_epochs=<span class="hljs-number">10</span>,
<span class="hljs-meta">... </span>    fp16=<span class="hljs-literal">True</span>,
<span class="hljs-meta">... </span>    save_steps=<span class="hljs-number">200</span>,
<span class="hljs-meta">... </span>    logging_steps=<span class="hljs-number">50</span>,
<span class="hljs-meta">... </span>    learning_rate=<span class="hljs-number">1e-5</span>,
<span class="hljs-meta">... </span>    weight_decay=<span class="hljs-number">1e-4</span>,
<span class="hljs-meta">... </span>    save_total_limit=<span class="hljs-number">2</span>,
<span class="hljs-meta">... </span>    remove_unused_columns=<span class="hljs-literal">False</span>,
<span class="hljs-meta">... </span>    push_to_hub=<span class="hljs-literal">True</span>,
<span class="hljs-meta">... </span>)`}}),ha=new _({props:{code:`from transformers import Trainer

trainer = Trainer(
    model=model,
    args=training_args,
    data_collator=collate_fn,
    train_dataset=cppe5["train"],
    tokenizer=image_processor,
)

trainer.train()`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> Trainer

<span class="hljs-meta">&gt;&gt;&gt; </span>trainer = Trainer(
<span class="hljs-meta">... </span>    model=model,
<span class="hljs-meta">... </span>    args=training_args,
<span class="hljs-meta">... </span>    data_collator=collate_fn,
<span class="hljs-meta">... </span>    train_dataset=cppe5[<span class="hljs-string">&quot;train&quot;</span>],
<span class="hljs-meta">... </span>    tokenizer=image_processor,
<span class="hljs-meta">... </span>)

<span class="hljs-meta">&gt;&gt;&gt; </span>trainer.train()`}}),ma=new _({props:{code:"trainer.push_to_hub()",highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>trainer.push_to_hub()'}}),ua=new me({}),ga=new _({props:{code:`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],
            "iscrowd": 0,
            "image_id": image_id,
            "area": objects["area"][i],
            "bbox": objects["bbox"][i],
        }
        annotations.append(new_ann)

    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/"

    if not os.path.exists(path_output_cppe5):
        os.makedirs(path_output_cppe5)

    path_anno = os.path.join(path_output_cppe5, "cppe5_ann.json")
    categories_json = [{"supercategory": "none", "id": id, "name": id2label[id]} for id in id2label]
    output_json["images"] = []
    output_json["annotations"] = []
    for example in cppe5:
        ann = val_formatted_anns(example["image_id"], example["objects"])
        output_json["images"].append(
            {
                "id": example["image_id"],
                "width": example["image"].width,
                "height": example["image"].height,
                "file_name": f"{example['image_id']}.png",
            }
        )
        output_json["annotations"].extend(ann)
    output_json["categories"] = categories_json

    with open(path_anno, "w") as file:
        json.dump(output_json, file, ensure_ascii=False, indent=4)

    for im, img_id in zip(cppe5["image"], cppe5["image_id"]):
        path_img = os.path.join(path_output_cppe5, f"{img_id}.png")
        im.save(path_img)

    return path_output_cppe5, path_anno`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> json


<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-comment"># format annotations the same as for training, no need for data augmentation</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">val_formatted_anns</span>(<span class="hljs-params">image_id, objects</span>):
<span class="hljs-meta">... </span>    annotations = []
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">0</span>, <span class="hljs-built_in">len</span>(objects[<span class="hljs-string">&quot;id&quot;</span>])):
<span class="hljs-meta">... </span>        new_ann = {
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;id&quot;</span>: objects[<span class="hljs-string">&quot;id&quot;</span>][i],
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;category_id&quot;</span>: objects[<span class="hljs-string">&quot;category&quot;</span>][i],
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;iscrowd&quot;</span>: <span class="hljs-number">0</span>,
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;image_id&quot;</span>: image_id,
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;area&quot;</span>: objects[<span class="hljs-string">&quot;area&quot;</span>][i],
<span class="hljs-meta">... </span>            <span class="hljs-string">&quot;bbox&quot;</span>: objects[<span class="hljs-string">&quot;bbox&quot;</span>][i],
<span class="hljs-meta">... </span>        }
<span class="hljs-meta">... </span>        annotations.append(new_ann)

<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> annotations


<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-comment"># Save images and annotations into the files torchvision.datasets.CocoDetection expects</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">save_cppe5_annotation_file_images</span>(<span class="hljs-params">cppe5</span>):
<span class="hljs-meta">... </span>    output_json = {}
<span class="hljs-meta">... </span>    path_output_cppe5 = <span class="hljs-string">f&quot;<span class="hljs-subst">{os.getcwd()}</span>/cppe5/&quot;</span>

<span class="hljs-meta">... </span>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(path_output_cppe5):
<span class="hljs-meta">... </span>        os.makedirs(path_output_cppe5)

<span class="hljs-meta">... </span>    path_anno = os.path.join(path_output_cppe5, <span class="hljs-string">&quot;cppe5_ann.json&quot;</span>)
<span class="hljs-meta">... </span>    categories_json = [{<span class="hljs-string">&quot;supercategory&quot;</span>: <span class="hljs-string">&quot;none&quot;</span>, <span class="hljs-string">&quot;id&quot;</span>: <span class="hljs-built_in">id</span>, <span class="hljs-string">&quot;name&quot;</span>: id2label[<span class="hljs-built_in">id</span>]} <span class="hljs-keyword">for</span> <span class="hljs-built_in">id</span> <span class="hljs-keyword">in</span> id2label]
<span class="hljs-meta">... </span>    output_json[<span class="hljs-string">&quot;images&quot;</span>] = []
<span class="hljs-meta">... </span>    output_json[<span class="hljs-string">&quot;annotations&quot;</span>] = []
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> example <span class="hljs-keyword">in</span> cppe5:
<span class="hljs-meta">... </span>        ann = val_formatted_anns(example[<span class="hljs-string">&quot;image_id&quot;</span>], example[<span class="hljs-string">&quot;objects&quot;</span>])
<span class="hljs-meta">... </span>        output_json[<span class="hljs-string">&quot;images&quot;</span>].append(
<span class="hljs-meta">... </span>            {
<span class="hljs-meta">... </span>                <span class="hljs-string">&quot;id&quot;</span>: example[<span class="hljs-string">&quot;image_id&quot;</span>],
<span class="hljs-meta">... </span>                <span class="hljs-string">&quot;width&quot;</span>: example[<span class="hljs-string">&quot;image&quot;</span>].width,
<span class="hljs-meta">... </span>                <span class="hljs-string">&quot;height&quot;</span>: example[<span class="hljs-string">&quot;image&quot;</span>].height,
<span class="hljs-meta">... </span>                <span class="hljs-string">&quot;file_name&quot;</span>: <span class="hljs-string">f&quot;<span class="hljs-subst">{example[<span class="hljs-string">&#x27;image_id&#x27;</span>]}</span>.png&quot;</span>,
<span class="hljs-meta">... </span>            }
<span class="hljs-meta">... </span>        )
<span class="hljs-meta">... </span>        output_json[<span class="hljs-string">&quot;annotations&quot;</span>].extend(ann)
<span class="hljs-meta">... </span>    output_json[<span class="hljs-string">&quot;categories&quot;</span>] = categories_json

<span class="hljs-meta">... </span>    <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(path_anno, <span class="hljs-string">&quot;w&quot;</span>) <span class="hljs-keyword">as</span> file:
<span class="hljs-meta">... </span>        json.dump(output_json, file, ensure_ascii=<span class="hljs-literal">False</span>, indent=<span class="hljs-number">4</span>)

<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> im, img_id <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(cppe5[<span class="hljs-string">&quot;image&quot;</span>], cppe5[<span class="hljs-string">&quot;image_id&quot;</span>]):
<span class="hljs-meta">... </span>        path_img = os.path.join(path_output_cppe5, <span class="hljs-string">f&quot;<span class="hljs-subst">{img_id}</span>.png&quot;</span>)
<span class="hljs-meta">... </span>        im.save(path_img)

<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> path_output_cppe5, path_anno`}}),fa=new _({props:{code:`import torchvision


class CocoDetection(torchvision.datasets.CocoDetection):
    def __init__(self, img_folder, feature_extractor, ann_file):
        super().__init__(img_folder, ann_file)
        self.feature_extractor = feature_extractor

    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]
        target = {"image_id": image_id, "annotations": target}
        encoding = self.feature_extractor(images=img, annotations=target, return_tensors="pt")
        pixel_values = encoding["pixel_values"].squeeze()  # remove batch dimension
        target = encoding["labels"][0]  # remove batch dimension

        return {"pixel_values": pixel_values, "labels": target}


im_processor = AutoImageProcessor.from_pretrained("MariaK/detr-resnet-50_finetuned_cppe5")

path_output_cppe5, path_anno = save_cppe5_annotation_file_images(cppe5["test"])
test_ds_coco_format = CocoDetection(path_output_cppe5, im_processor, path_anno)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torchvision


<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">class</span> <span class="hljs-title class_">CocoDetection</span>(torchvision.datasets.CocoDetection):
<span class="hljs-meta">... </span>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, img_folder, feature_extractor, ann_file</span>):
<span class="hljs-meta">... </span>        <span class="hljs-built_in">super</span>().__init__(img_folder, ann_file)
<span class="hljs-meta">... </span>        self.feature_extractor = feature_extractor

<span class="hljs-meta">... </span>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__getitem__</span>(<span class="hljs-params">self, idx</span>):
<span class="hljs-meta">... </span>        <span class="hljs-comment"># read in PIL image and target in COCO format</span>
<span class="hljs-meta">... </span>        img, target = <span class="hljs-built_in">super</span>(CocoDetection, self).__getitem__(idx)

<span class="hljs-meta">... </span>        <span class="hljs-comment"># preprocess image and target: converting target to DETR format,</span>
<span class="hljs-meta">... </span>        <span class="hljs-comment"># resizing + normalization of both image and target)</span>
<span class="hljs-meta">... </span>        image_id = self.ids[idx]
<span class="hljs-meta">... </span>        target = {<span class="hljs-string">&quot;image_id&quot;</span>: image_id, <span class="hljs-string">&quot;annotations&quot;</span>: target}
<span class="hljs-meta">... </span>        encoding = self.feature_extractor(images=img, annotations=target, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
<span class="hljs-meta">... </span>        pixel_values = encoding[<span class="hljs-string">&quot;pixel_values&quot;</span>].squeeze()  <span class="hljs-comment"># remove batch dimension</span>
<span class="hljs-meta">... </span>        target = encoding[<span class="hljs-string">&quot;labels&quot;</span>][<span class="hljs-number">0</span>]  <span class="hljs-comment"># remove batch dimension</span>

<span class="hljs-meta">... </span>        <span class="hljs-keyword">return</span> {<span class="hljs-string">&quot;pixel_values&quot;</span>: pixel_values, <span class="hljs-string">&quot;labels&quot;</span>: target}


<span class="hljs-meta">&gt;&gt;&gt; </span>im_processor = AutoImageProcessor.from_pretrained(<span class="hljs-string">&quot;MariaK/detr-resnet-50_finetuned_cppe5&quot;</span>)

<span class="hljs-meta">&gt;&gt;&gt; </span>path_output_cppe5, path_anno = save_cppe5_annotation_file_images(cppe5[<span class="hljs-string">&quot;test&quot;</span>])
<span class="hljs-meta">&gt;&gt;&gt; </span>test_ds_coco_format = CocoDetection(path_output_cppe5, im_processor, path_anno)`}}),ja=new _({props:{code:`import evaluate
from tqdm import tqdm

model = AutoModelForObjectDetection.from_pretrained("MariaK/detr-resnet-50_finetuned_cppe5")
module = evaluate.load("ybelkada/cocoevaluate", coco=test_ds_coco_format.coco)
val_dataloader = torch.utils.data.DataLoader(
    test_ds_coco_format, batch_size=8, shuffle=False, num_workers=4, collate_fn=collate_fn
)

with torch.no_grad():
    for idx, batch in enumerate(tqdm(val_dataloader)):
        pixel_values = batch["pixel_values"]
        pixel_mask = batch["pixel_mask"]

        labels = [
            {k: v for k, v in t.items()} for t in batch["labels"]
        ]  # these are in DETR format, resized + normalized

        # forward pass
        outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask)

        orig_target_sizes = torch.stack([target["orig_size"] for target in labels], dim=0)
        results = im_processor.post_process(outputs, orig_target_sizes)  # convert outputs of model to COCO api

        module.add(prediction=results, reference=labels)
        del batch

results = module.compute()
print(results)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> evaluate
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> tqdm <span class="hljs-keyword">import</span> tqdm

<span class="hljs-meta">&gt;&gt;&gt; </span>model = AutoModelForObjectDetection.from_pretrained(<span class="hljs-string">&quot;MariaK/detr-resnet-50_finetuned_cppe5&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>module = evaluate.load(<span class="hljs-string">&quot;ybelkada/cocoevaluate&quot;</span>, coco=test_ds_coco_format.coco)
<span class="hljs-meta">&gt;&gt;&gt; </span>val_dataloader = torch.utils.data.DataLoader(
<span class="hljs-meta">... </span>    test_ds_coco_format, batch_size=<span class="hljs-number">8</span>, shuffle=<span class="hljs-literal">False</span>, num_workers=<span class="hljs-number">4</span>, collate_fn=collate_fn
<span class="hljs-meta">... </span>)

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">with</span> torch.no_grad():
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> idx, batch <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(tqdm(val_dataloader)):
<span class="hljs-meta">... </span>        pixel_values = batch[<span class="hljs-string">&quot;pixel_values&quot;</span>]
<span class="hljs-meta">... </span>        pixel_mask = batch[<span class="hljs-string">&quot;pixel_mask&quot;</span>]

<span class="hljs-meta">... </span>        labels = [
<span class="hljs-meta">... </span>            {k: v <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> t.items()} <span class="hljs-keyword">for</span> t <span class="hljs-keyword">in</span> batch[<span class="hljs-string">&quot;labels&quot;</span>]
<span class="hljs-meta">... </span>        ]  <span class="hljs-comment"># these are in DETR format, resized + normalized</span>

<span class="hljs-meta">... </span>        <span class="hljs-comment"># forward pass</span>
<span class="hljs-meta">... </span>        outputs = model(pixel_values=pixel_values, pixel_mask=pixel_mask)

<span class="hljs-meta">... </span>        orig_target_sizes = torch.stack([target[<span class="hljs-string">&quot;orig_size&quot;</span>] <span class="hljs-keyword">for</span> target <span class="hljs-keyword">in</span> labels], dim=<span class="hljs-number">0</span>)
<span class="hljs-meta">... </span>        results = im_processor.post_process(outputs, orig_target_sizes)  <span class="hljs-comment"># convert outputs of model to COCO api</span>

<span class="hljs-meta">... </span>        module.add(prediction=results, reference=labels)
<span class="hljs-meta">... </span>        <span class="hljs-keyword">del</span> batch

<span class="hljs-meta">&gt;&gt;&gt; </span>results = module.compute()
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(results)
Accumulating evaluation results...
DONE (t=<span class="hljs-number">0.08</span>s).
IoU metric: bbox
 Average Precision  (AP) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area=   <span class="hljs-built_in">all</span> | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.150</span>
 Average Precision  (AP) @[ IoU=<span class="hljs-number">0.50</span>      | area=   <span class="hljs-built_in">all</span> | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.280</span>
 Average Precision  (AP) @[ IoU=<span class="hljs-number">0.75</span>      | area=   <span class="hljs-built_in">all</span> | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.130</span>
 Average Precision  (AP) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area= small | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.038</span>
 Average Precision  (AP) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area=medium | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.036</span>
 Average Precision  (AP) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area= large | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.182</span>
 Average Recall     (AR) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area=   <span class="hljs-built_in">all</span> | maxDets=  <span class="hljs-number">1</span> ] = <span class="hljs-number">0.166</span>
 Average Recall     (AR) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area=   <span class="hljs-built_in">all</span> | maxDets= <span class="hljs-number">10</span> ] = <span class="hljs-number">0.317</span>
 Average Recall     (AR) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area=   <span class="hljs-built_in">all</span> | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.335</span>
 Average Recall     (AR) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area= small | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.104</span>
 Average Recall     (AR) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area=medium | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.146</span>
 Average Recall     (AR) @[ IoU=<span class="hljs-number">0.50</span>:<span class="hljs-number">0.95</span> | area= large | maxDets=<span class="hljs-number">100</span> ] = <span class="hljs-number">0.382</span>`}}),ba=new me({}),_a=new _({props:{code:`from transformers import pipeline
import requests

url = "https://i.imgur.com/2lnWoly.jpg"
image = Image.open(requests.get(url, stream=True).raw)

obj_detector = pipeline("object-detection", model="MariaK/detr-resnet-50_finetuned_cppe5")
obj_detector(image)`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> requests

<span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">&quot;https://i.imgur.com/2lnWoly.jpg&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>image = Image.<span class="hljs-built_in">open</span>(requests.get(url, stream=<span class="hljs-literal">True</span>).raw)

<span class="hljs-meta">&gt;&gt;&gt; </span>obj_detector = pipeline(<span class="hljs-string">&quot;object-detection&quot;</span>, model=<span class="hljs-string">&quot;MariaK/detr-resnet-50_finetuned_cppe5&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>obj_detector(image)`}}),va=new _({props:{code:`image_processor = AutoImageProcessor.from_pretrained("MariaK/detr-resnet-50_finetuned_cppe5")
model = AutoModelForObjectDetection.from_pretrained("MariaK/detr-resnet-50_finetuned_cppe5")

with torch.no_grad():
    inputs = image_processor(images=image, return_tensors="pt")
    outputs = model(**inputs)
    target_sizes = torch.tensor([image.size[::-1]])
    results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[0]

for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
    box = [round(i, 2) for i in box.tolist()]
    print(
        f"Detected {model.config.id2label[label.item()]} with confidence "
        f"{round(score.item(), 3)} at location {box}"
    )`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>image_processor = AutoImageProcessor.from_pretrained(<span class="hljs-string">&quot;MariaK/detr-resnet-50_finetuned_cppe5&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>model = AutoModelForObjectDetection.from_pretrained(<span class="hljs-string">&quot;MariaK/detr-resnet-50_finetuned_cppe5&quot;</span>)

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">with</span> torch.no_grad():
<span class="hljs-meta">... </span>    inputs = image_processor(images=image, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
<span class="hljs-meta">... </span>    outputs = model(**inputs)
<span class="hljs-meta">... </span>    target_sizes = torch.tensor([image.size[::-<span class="hljs-number">1</span>]])
<span class="hljs-meta">... </span>    results = image_processor.post_process_object_detection(outputs, threshold=<span class="hljs-number">0.5</span>, target_sizes=target_sizes)[<span class="hljs-number">0</span>]

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> score, label, box <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(results[<span class="hljs-string">&quot;scores&quot;</span>], results[<span class="hljs-string">&quot;labels&quot;</span>], results[<span class="hljs-string">&quot;boxes&quot;</span>]):
<span class="hljs-meta">... </span>    box = [<span class="hljs-built_in">round</span>(i, <span class="hljs-number">2</span>) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> box.tolist()]
<span class="hljs-meta">... </span>    <span class="hljs-built_in">print</span>(
<span class="hljs-meta">... </span>        <span class="hljs-string">f&quot;Detected <span class="hljs-subst">{model.config.id2label[label.item()]}</span> with confidence &quot;</span>
<span class="hljs-meta">... </span>        <span class="hljs-string">f&quot;<span class="hljs-subst">{<span class="hljs-built_in">round</span>(score.item(), <span class="hljs-number">3</span>)}</span> at location <span class="hljs-subst">{box}</span>&quot;</span>
<span class="hljs-meta">... </span>    )
Detected Coverall <span class="hljs-keyword">with</span> confidence <span class="hljs-number">0.566</span> at location [<span class="hljs-number">1215.32</span>, <span class="hljs-number">147.38</span>, <span class="hljs-number">4401.81</span>, <span class="hljs-number">3227.08</span>]
Detected Mask <span class="hljs-keyword">with</span> confidence <span class="hljs-number">0.584</span> at location [<span class="hljs-number">2449.06</span>, <span class="hljs-number">823.19</span>, <span class="hljs-number">3256.43</span>, <span class="hljs-number">1413.9</span>]`}}),wa=new _({props:{code:`draw = ImageDraw.Draw(image)

for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
    box = [round(i, 2) for i in box.tolist()]
    x, y, x2, y2 = tuple(box)
    draw.rectangle((x, y, x2, y2), outline="red", width=1)
    draw.text((x, y), model.config.id2label[label.item()], fill="white")

image`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>draw = ImageDraw.Draw(image)

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> score, label, box <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(results[<span class="hljs-string">&quot;scores&quot;</span>], results[<span class="hljs-string">&quot;labels&quot;</span>], results[<span class="hljs-string">&quot;boxes&quot;</span>]):
<span class="hljs-meta">... </span>    box = [<span class="hljs-built_in">round</span>(i, <span class="hljs-number">2</span>) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> box.tolist()]
<span class="hljs-meta">... </span>    x, y, x2, y2 = <span class="hljs-built_in">tuple</span>(box)
<span class="hljs-meta">... </span>    draw.rectangle((x, y, x2, y2), outline=<span class="hljs-string">&quot;red&quot;</span>, width=<span class="hljs-number">1</span>)
<span class="hljs-meta">... </span>    draw.text((x, y), model.config.id2label[label.item()], fill=<span class="hljs-string">&quot;white&quot;</span>)

<span class="hljs-meta">&gt;&gt;&gt; </span>image`}}),{c(){$=l("meta"),v=c(),q=l("h1"),P=l("a"),ls=l("span"),u(D.$$.fragment),zs=c(),os=l("span"),G=t("Object detection"),ms=c(),u(M.$$.fragment),S=c(),B=l("p"),Fs=t(`Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output
coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,
each with its own bounding box and a label (e.g. it can have a car and a building), and each object can
be present in different parts of an image (e.g. the image can have several cars).
This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.
Other applications include counting objects in images, image search, and more.`),U=c(),K=l("p"),Ls=t("In this guide, you will learn how to:"),Y=c(),A=l("ol"),x=l("li"),y=t("Finetune "),W=l("a"),qa=t("DETR"),Ea=t(`, a model that combines a convolutional
backbone with an encoder-decoder Transformer, on the `),J=l("a"),ka=t("CPPE-5"),$a=t(`
dataset.`),ul=c(),ue=l("li"),dl=t("Use your finetuned model for inference."),Ot=c(),u(us.$$.fragment),Pt=c(),Da=l("p"),gl=t("Before you begin, make sure you have all the necessary libraries installed:"),At=c(),u(Rs.$$.fragment),It=c(),V=l("p"),fl=t(`You\u2019ll use \u{1F917} Datasets to load a dataset from the Hugging Face Hub, \u{1F917} Transformers to train your model,
and `),de=l("code"),jl=t("albumentations"),bl=t(" to augment the data. "),ge=l("code"),_l=t("timm"),vl=t(" is currently required to load a convolutional backbone for the DETR model."),zt=c(),Ta=l("p"),wl=t(`We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.
When prompted, enter your token to log in:`),Ft=c(),u(Hs.$$.fragment),Lt=c(),ps=l("h2"),ds=l("a"),fe=l("span"),u(Ms.$$.fragment),yl=c(),je=l("span"),xl=t("Load the CPPE-5 dataset"),Rt=c(),gs=l("p"),ql=t("The "),Ss=l("a"),El=t("CPPE-5 dataset"),kl=t(` contains images with
annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.`),Ht=c(),Ca=l("p"),$l=t("Start by loading the dataset:"),Mt=c(),u(Us.$$.fragment),St=c(),Oa=l("p"),Dl=t("You\u2019ll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images."),Ut=c(),Pa=l("p"),Tl=t("To get familiar with the data, explore what the examples look like."),Yt=c(),u(Ys.$$.fragment),Nt=c(),Aa=l("p"),Cl=t("The examples in the dataset have the following fields:"),Gt=c(),T=l("ul"),Ia=l("li"),be=l("code"),Ol=t("image_id"),Pl=t(": the example image id"),Al=c(),fs=l("li"),_e=l("code"),Il=t("image"),zl=t(": a "),ve=l("code"),Fl=t("PIL.Image.Image"),Ll=t(" object containing the image"),Rl=c(),za=l("li"),we=l("code"),Hl=t("width"),Ml=t(": width of the image"),Sl=c(),Fa=l("li"),ye=l("code"),Ul=t("height"),Yl=t(": height of the image"),Nl=c(),Ns=l("li"),xe=l("code"),Gl=t("objects"),Bl=t(": a dictionary containing bounding box metadata for the objects in the image:"),N=l("ul"),La=l("li"),qe=l("code"),Kl=t("id"),Wl=t(": the annotation id"),Jl=c(),Ra=l("li"),Ee=l("code"),Vl=t("area"),Ql=t(": the area of the bounding box"),Zl=c(),js=l("li"),ke=l("code"),Xl=t("bbox"),so=t(": the object\u2019s bounding box (in the "),Gs=l("a"),ao=t("COCO format"),eo=t(" )"),to=c(),k=l("li"),$e=l("code"),no=t("category"),lo=t(": the object\u2019s category, with possible values including "),De=l("code"),oo=t("Coverall (0)"),po=t(", "),Te=l("code"),ro=t("Face_Shield (1)"),io=t(", "),Ce=l("code"),co=t("Gloves (2)"),ho=t(", "),Oe=l("code"),mo=t("Goggles (3)"),uo=t(" and "),Pe=l("code"),go=t("Mask (4)"),Bt=c(),Q=l("p"),fo=t("You may notice that the "),Ae=l("code"),jo=t("bbox"),bo=t(` field follows the COCO format, which is the format that the DETR model expects.
However, the grouping of the fields inside `),Ie=l("code"),_o=t("objects"),vo=t(` differs from the annotation format DETR requires. You will
need to apply some preprocessing transformations before using this data for training.`),Kt=c(),Ha=l("p"),wo=t("To get an even better understanding of the data, visualize an example in the dataset."),Wt=c(),u(Bs.$$.fragment),Jt=c(),Ks=l("div"),Ma=l("img"),Vt=c(),I=l("p"),yo=t(`To visualize the bounding boxes with associated labels, you can get the labels from the dataset\u2019s metadata, specifically
the `),ze=l("code"),xo=t("category"),qo=t(` field.
You\u2019ll also want to create dictionaries that map a label id to a label class (`),Fe=l("code"),Eo=t("id2label"),ko=t(") and the other way around ("),Le=l("code"),$o=t("label2id"),Do=t(`).
You can use them later when setting up the model. Including these maps will make your model reusable by others if you share
it on the Hugging Face Hub.`),Qt=c(),Sa=l("p"),To=t(`As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for
object detection is bounding boxes that \u201Cstretch\u201D beyond the edge of the image. Such \u201Crunaway\u201D bounding boxes can raise
errors during training and should be addressed at this stage. There are a few examples with this issue in this dataset.
To keep things simple in this guide, we remove these images from the data.`),Zt=c(),u(Ws.$$.fragment),Xt=c(),rs=l("h2"),bs=l("a"),Re=l("span"),u(Js.$$.fragment),Co=c(),He=l("span"),Oo=t("Preprocess the data"),sn=c(),C=l("p"),Po=t(`To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.
`),Ua=l("a"),Ao=t("AutoImageProcessor"),Io=t(" takes care of processing image data to create "),Me=l("code"),zo=t("pixel_values"),Fo=t(", "),Se=l("code"),Lo=t("pixel_mask"),Ro=t(`, and
`),Ue=l("code"),Ho=t("labels"),Mo=t(" that a DETR model can train with. The image processor has some attributes that you won\u2019t have to worry about:"),an=c(),_s=l("ul"),Ye=l("li"),Ne=l("code"),So=t("image_mean = [0.485, 0.456, 0.406 ]"),Uo=c(),Ge=l("li"),Be=l("code"),Yo=t("image_std = [0.229, 0.224, 0.225]"),en=c(),Ya=l("p"),No=t(`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.`),tn=c(),Na=l("p"),Go=t("Instantiate the image processor from the same checkpoint as the model you want to finetune."),nn=c(),u(Vs.$$.fragment),ln=c(),vs=l("p"),Bo=t("Before passing the images to the "),Ke=l("code"),Ko=t("image_processor"),Wo=t(", apply two preprocessing transformations to the dataset:"),on=c(),ws=l("ul"),We=l("li"),Jo=t("Augmenting images"),Vo=c(),Je=l("li"),Qo=t("Reformatting annotations to meet DETR expectations"),pn=c(),Z=l("p"),Zo=t("First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use "),Qs=l("a"),Xo=t("Albumentations"),sp=t(` \u2026
This library ensures that transformations affect the image and update the bounding boxes accordingly.
The \u{1F917} Datasets library documentation has a detailed `),Zs=l("a"),ap=t("guide on how to augment images for object detection"),ep=t(`,
and it uses the exact same dataset as an example. Apply the same approach here, resize each image to (480, 480),
flip it horizontally, and brighten it:`),rn=c(),u(Xs.$$.fragment),cn=c(),X=l("p"),tp=t("The "),Ve=l("code"),np=t("image_processor"),lp=t(" expects the annotations to be in the following format: "),Qe=l("code"),op=t("{'image_id': int, 'annotations': List[Dict]}"),pp=t(`,
where each dictionary is a COCO object annotation. Let\u2019s add a function to reformat annotations for a single example:`),hn=c(),u(sa.$$.fragment),mn=c(),Ga=l("p"),rp=t("Now you can combine the image and annotation transformations to use on a batch of examples:"),un=c(),u(aa.$$.fragment),dn=c(),ys=l("p"),ip=t("Apply this preprocessing function to the entire dataset using \u{1F917} Datasets "),Ze=l("code"),cp=t("with_transform"),hp=t(` method. This method applies
transformations on the fly when you load an element of the dataset.`),gn=c(),z=l("p"),mp=t(`At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor
with `),Xe=l("code"),up=t("pixel_values"),dp=t(", a tensor with "),st=l("code"),gp=t("pixel_mask"),fp=t(", and "),at=l("code"),jp=t("labels"),bp=t("."),fn=c(),u(ea.$$.fragment),jn=c(),F=l("p"),_p=t(`You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn\u2019t
complete yet. In the final step, create a custom `),et=l("code"),vp=t("collate_fn"),wp=t(` to batch images together.
Pad images (which are now `),tt=l("code"),yp=t("pixel_values"),xp=t(") to the largest image in a batch, and create a corresponding "),nt=l("code"),qp=t("pixel_mask"),Ep=t(`
to indicate which pixels are real (1) and which are padding (0).`),bn=c(),u(ta.$$.fragment),_n=c(),is=l("h2"),xs=l("a"),lt=l("span"),u(na.$$.fragment),kp=c(),ot=l("span"),$p=t("Training the DETR model"),vn=t(`

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.
`),Ba=l("p"),Dp=t("Training involves the following steps:"),wn=c(),L=l("ol"),la=l("li"),Tp=t("Load the model with "),Ka=l("a"),Cp=t("AutoModelForObjectDetection"),Op=t(" using the same checkpoint as in the preprocessing."),Pp=c(),oa=l("li"),Ap=t("Define your training hyperparameters in "),Wa=l("a"),Ip=t("TrainingArguments"),zp=t("."),Fp=c(),pa=l("li"),Lp=t("Pass the training arguments to "),Ja=l("a"),Rp=t("Trainer"),Hp=t(" along with the model, dataset, image processor, and data collator."),Mp=c(),ra=l("li"),Sp=t("Call "),Va=l("a"),Up=t("train()"),Yp=t(" to finetune your model."),yn=c(),R=l("p"),Np=t("When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the "),pt=l("code"),Gp=t("label2id"),Bp=t(`
and `),rt=l("code"),Kp=t("id2label"),Wp=t(" maps that you created earlier from the dataset\u2019s metadata. Additionally, we specify "),it=l("code"),Jp=t("ignore_mismatched_sizes=True"),Vp=t(" to replace the existing classification head with a new one."),xn=c(),u(ia.$$.fragment),qn=c(),w=l("p"),Qp=t("In the "),Qa=l("a"),Zp=t("TrainingArguments"),Xp=t(" use "),ct=l("code"),sr=t("output_dir"),ar=t(` 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\u2019t create `),ht=l("code"),er=t("pixel_values"),tr=t(". For this reason, set "),mt=l("code"),nr=t("remove_unused_columns"),lr=t(" to "),ut=l("code"),or=t("False"),pr=t(`.
If you wish to share your model by pushing to the Hub, set `),dt=l("code"),rr=t("push_to_hub"),ir=t(" to "),gt=l("code"),cr=t("True"),hr=t(` (you must be signed in to Hugging
Face to upload your model).`),En=c(),u(ca.$$.fragment),kn=c(),qs=l("p"),mr=t("Finally, bring everything together, and call "),Za=l("a"),ur=t("train()"),dr=t(":"),$n=c(),u(ha.$$.fragment),Dn=c(),O=l("p"),gr=t("If you have set "),ft=l("code"),fr=t("push_to_hub"),jr=t(" to "),jt=l("code"),br=t("True"),_r=t(" in the "),bt=l("code"),vr=t("training_args"),wr=t(`, 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 `),Xa=l("a"),yr=t("push_to_hub()"),xr=t(" method."),Tn=c(),u(ma.$$.fragment),Cn=c(),cs=l("h2"),Es=l("a"),_t=l("span"),u(ua.$$.fragment),qr=c(),vt=l("span"),Er=t("Evaluate"),On=t(`

Object detection models are commonly evaluated with a set of `),da=l("a"),kr=t("COCO-style metrics"),Pn=t(`.
You can use one of the existing metrics implementations, but here you'll use the one from \`torchvision\` to evaluate the final
model that you pushed to the Hub.
`),ss=l("p"),$r=t("To use the "),wt=l("code"),Dr=t("torchvision"),Tr=t(` evaluator, you\u2019ll need to prepare a ground truth COCO dataset. The API to build a COCO dataset
requires the data to be stored in a certain format, so you\u2019ll need to save images and annotations to disk first. Just like
when you prepared your data for training, the annotations from the `),yt=l("code"),Cr=t('cppe5["test"]'),Or=t(` need to be formatted. However, images
should stay as they are.`),An=c(),ks=l("p"),Pr=t(`The evaluation step requires a bit of work, but it can be split in three major steps.
First, prepare the `),xt=l("code"),Ar=t('cppe5["test"]'),Ir=t(" set: format the annotations and save the data to disk."),In=c(),u(ga.$$.fragment),zn=c(),as=l("p"),zr=t("Next, prepare an instance of a "),qt=l("code"),Fr=t("CocoDetection"),Lr=t(" class that can be used with "),Et=l("code"),Rr=t("cocoevaluator"),Hr=t("."),Fn=c(),u(fa.$$.fragment),Ln=c(),se=l("p"),Mr=t("Finally, load the metrics and run the evaluation."),Rn=c(),u(ja.$$.fragment),Hn=c(),$s=l("p"),Sr=t("These results can be further improved by adjusting the hyperparameters in "),ae=l("a"),Ur=t("TrainingArguments"),Yr=t(". Give it a go!"),Mn=c(),hs=l("h2"),Ds=l("a"),kt=l("span"),u(ba.$$.fragment),Nr=c(),$t=l("span"),Gr=t("Inference"),Sn=t(`

Now that you have finetuned a DETR model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.
The simplest way to try out your finetuned model for inference is to use it in a [Pipeline](/docs/transformers/v4.27.1/en/main_classes/pipelines#transformers.Pipeline). Instantiate a pipeline
for object detection with your model, and pass an image to it:

	`),u(_a.$$.fragment),Un=c(),ee=l("p"),Br=t("You can also manually replicate the results of the pipeline if you\u2019d like:"),Yn=c(),u(va.$$.fragment),Nn=c(),te=l("p"),Kr=t("Let\u2019s plot the result:"),Gn=c(),u(wa.$$.fragment),Bn=c(),ya=l("div"),ne=l("img"),this.h()},l(s){const r=ih('[data-svelte="svelte-1phssyn"]',document.head);$=o(r,"META",{name:!0,content:!0}),r.forEach(e),v=h(s),q=o(s,"H1",{class:!0});var xa=p(q);P=o(xa,"A",{id:!0,class:!0,href:!0});var ai=p(P);ls=o(ai,"SPAN",{});var ei=p(ls);d(D.$$.fragment,ei),ei.forEach(e),ai.forEach(e),zs=h(xa),os=o(xa,"SPAN",{});var ti=p(os);G=n(ti,"Object detection"),ti.forEach(e),xa.forEach(e),ms=h(s),d(M.$$.fragment,s),S=h(s),B=o(s,"P",{});var ni=p(B);Fs=n(ni,`Object detection is the computer vision task of detecting instances (such as humans, buildings, or cars) in an image. Object detection models receive an image as input and output
coordinates of the bounding boxes and associated labels of the detected objects. An image can contain multiple objects,
each with its own bounding box and a label (e.g. it can have a car and a building), and each object can
be present in different parts of an image (e.g. the image can have several cars).
This task is commonly used in autonomous driving for detecting things like pedestrians, road signs, and traffic lights.
Other applications include counting objects in images, image search, and more.`),ni.forEach(e),U=h(s),K=o(s,"P",{});var li=p(K);Ls=n(li,"In this guide, you will learn how to:"),li.forEach(e),Y=h(s),A=o(s,"OL",{});var Wn=p(A);x=o(Wn,"LI",{});var le=p(x);y=n(le,"Finetune "),W=o(le,"A",{href:!0,rel:!0});var oi=p(W);qa=n(oi,"DETR"),oi.forEach(e),Ea=n(le,`, a model that combines a convolutional
backbone with an encoder-decoder Transformer, on the `),J=o(le,"A",{href:!0,rel:!0});var pi=p(J);ka=n(pi,"CPPE-5"),pi.forEach(e),$a=n(le,`
dataset.`),le.forEach(e),ul=h(Wn),ue=o(Wn,"LI",{});var ri=p(ue);dl=n(ri,"Use your finetuned model for inference."),ri.forEach(e),Wn.forEach(e),Ot=h(s),d(us.$$.fragment,s),Pt=h(s),Da=o(s,"P",{});var ii=p(Da);gl=n(ii,"Before you begin, make sure you have all the necessary libraries installed:"),ii.forEach(e),At=h(s),d(Rs.$$.fragment,s),It=h(s),V=o(s,"P",{});var oe=p(V);fl=n(oe,`You\u2019ll use \u{1F917} Datasets to load a dataset from the Hugging Face Hub, \u{1F917} Transformers to train your model,
and `),de=o(oe,"CODE",{});var ci=p(de);jl=n(ci,"albumentations"),ci.forEach(e),bl=n(oe," to augment the data. "),ge=o(oe,"CODE",{});var hi=p(ge);_l=n(hi,"timm"),hi.forEach(e),vl=n(oe," is currently required to load a convolutional backbone for the DETR model."),oe.forEach(e),zt=h(s),Ta=o(s,"P",{});var mi=p(Ta);wl=n(mi,`We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the Hub.
When prompted, enter your token to log in:`),mi.forEach(e),Ft=h(s),d(Hs.$$.fragment,s),Lt=h(s),ps=o(s,"H2",{class:!0});var Jn=p(ps);ds=o(Jn,"A",{id:!0,class:!0,href:!0});var ui=p(ds);fe=o(ui,"SPAN",{});var di=p(fe);d(Ms.$$.fragment,di),di.forEach(e),ui.forEach(e),yl=h(Jn),je=o(Jn,"SPAN",{});var gi=p(je);xl=n(gi,"Load the CPPE-5 dataset"),gi.forEach(e),Jn.forEach(e),Rt=h(s),gs=o(s,"P",{});var Vn=p(gs);ql=n(Vn,"The "),Ss=o(Vn,"A",{href:!0,rel:!0});var fi=p(Ss);El=n(fi,"CPPE-5 dataset"),fi.forEach(e),kl=n(Vn,` contains images with
annotations identifying medical personal protective equipment (PPE) in the context of the COVID-19 pandemic.`),Vn.forEach(e),Ht=h(s),Ca=o(s,"P",{});var ji=p(Ca);$l=n(ji,"Start by loading the dataset:"),ji.forEach(e),Mt=h(s),d(Us.$$.fragment,s),St=h(s),Oa=o(s,"P",{});var bi=p(Oa);Dl=n(bi,"You\u2019ll see that this dataset already comes with a training set containing 1000 images and a test set with 29 images."),bi.forEach(e),Ut=h(s),Pa=o(s,"P",{});var _i=p(Pa);Tl=n(_i,"To get familiar with the data, explore what the examples look like."),_i.forEach(e),Yt=h(s),d(Ys.$$.fragment,s),Nt=h(s),Aa=o(s,"P",{});var vi=p(Aa);Cl=n(vi,"The examples in the dataset have the following fields:"),vi.forEach(e),Gt=h(s),T=o(s,"UL",{});var es=p(T);Ia=o(es,"LI",{});var Wr=p(Ia);be=o(Wr,"CODE",{});var wi=p(be);Ol=n(wi,"image_id"),wi.forEach(e),Pl=n(Wr,": the example image id"),Wr.forEach(e),Al=h(es),fs=o(es,"LI",{});var Dt=p(fs);_e=o(Dt,"CODE",{});var yi=p(_e);Il=n(yi,"image"),yi.forEach(e),zl=n(Dt,": a "),ve=o(Dt,"CODE",{});var xi=p(ve);Fl=n(xi,"PIL.Image.Image"),xi.forEach(e),Ll=n(Dt," object containing the image"),Dt.forEach(e),Rl=h(es),za=o(es,"LI",{});var Jr=p(za);we=o(Jr,"CODE",{});var qi=p(we);Hl=n(qi,"width"),qi.forEach(e),Ml=n(Jr,": width of the image"),Jr.forEach(e),Sl=h(es),Fa=o(es,"LI",{});var Vr=p(Fa);ye=o(Vr,"CODE",{});var Ei=p(ye);Ul=n(Ei,"height"),Ei.forEach(e),Yl=n(Vr,": height of the image"),Vr.forEach(e),Nl=h(es),Ns=o(es,"LI",{});var Qn=p(Ns);xe=o(Qn,"CODE",{});var ki=p(xe);Gl=n(ki,"objects"),ki.forEach(e),Bl=n(Qn,": a dictionary containing bounding box metadata for the objects in the image:"),N=o(Qn,"UL",{});var Ts=p(N);La=o(Ts,"LI",{});var Qr=p(La);qe=o(Qr,"CODE",{});var $i=p(qe);Kl=n($i,"id"),$i.forEach(e),Wl=n(Qr,": the annotation id"),Qr.forEach(e),Jl=h(Ts),Ra=o(Ts,"LI",{});var Zr=p(Ra);Ee=o(Zr,"CODE",{});var Di=p(Ee);Vl=n(Di,"area"),Di.forEach(e),Ql=n(Zr,": the area of the bounding box"),Zr.forEach(e),Zl=h(Ts),js=o(Ts,"LI",{});var Tt=p(js);ke=o(Tt,"CODE",{});var Ti=p(ke);Xl=n(Ti,"bbox"),Ti.forEach(e),so=n(Tt,": the object\u2019s bounding box (in the "),Gs=o(Tt,"A",{href:!0,rel:!0});var Ci=p(Gs);ao=n(Ci,"COCO format"),Ci.forEach(e),eo=n(Tt," )"),Tt.forEach(e),to=h(Ts),k=o(Ts,"LI",{});var H=p(k);$e=o(H,"CODE",{});var Oi=p($e);no=n(Oi,"category"),Oi.forEach(e),lo=n(H,": the object\u2019s category, with possible values including "),De=o(H,"CODE",{});var Pi=p(De);oo=n(Pi,"Coverall (0)"),Pi.forEach(e),po=n(H,", "),Te=o(H,"CODE",{});var Ai=p(Te);ro=n(Ai,"Face_Shield (1)"),Ai.forEach(e),io=n(H,", "),Ce=o(H,"CODE",{});var Ii=p(Ce);co=n(Ii,"Gloves (2)"),Ii.forEach(e),ho=n(H,", "),Oe=o(H,"CODE",{});var zi=p(Oe);mo=n(zi,"Goggles (3)"),zi.forEach(e),uo=n(H," and "),Pe=o(H,"CODE",{});var Fi=p(Pe);go=n(Fi,"Mask (4)"),Fi.forEach(e),H.forEach(e),Ts.forEach(e),Qn.forEach(e),es.forEach(e),Bt=h(s),Q=o(s,"P",{});var pe=p(Q);fo=n(pe,"You may notice that the "),Ae=o(pe,"CODE",{});var Li=p(Ae);jo=n(Li,"bbox"),Li.forEach(e),bo=n(pe,` field follows the COCO format, which is the format that the DETR model expects.
However, the grouping of the fields inside `),Ie=o(pe,"CODE",{});var Ri=p(Ie);_o=n(Ri,"objects"),Ri.forEach(e),vo=n(pe,` differs from the annotation format DETR requires. You will
need to apply some preprocessing transformations before using this data for training.`),pe.forEach(e),Kt=h(s),Ha=o(s,"P",{});var Hi=p(Ha);wo=n(Hi,"To get an even better understanding of the data, visualize an example in the dataset."),Hi.forEach(e),Wt=h(s),d(Bs.$$.fragment,s),Jt=h(s),Ks=o(s,"DIV",{class:!0});var Mi=p(Ks);Ma=o(Mi,"IMG",{src:!0,alt:!0}),Mi.forEach(e),Vt=h(s),I=o(s,"P",{});var Cs=p(I);yo=n(Cs,`To visualize the bounding boxes with associated labels, you can get the labels from the dataset\u2019s metadata, specifically
the `),ze=o(Cs,"CODE",{});var Si=p(ze);xo=n(Si,"category"),Si.forEach(e),qo=n(Cs,` field.
You\u2019ll also want to create dictionaries that map a label id to a label class (`),Fe=o(Cs,"CODE",{});var Ui=p(Fe);Eo=n(Ui,"id2label"),Ui.forEach(e),ko=n(Cs,") and the other way around ("),Le=o(Cs,"CODE",{});var Yi=p(Le);$o=n(Yi,"label2id"),Yi.forEach(e),Do=n(Cs,`).
You can use them later when setting up the model. Including these maps will make your model reusable by others if you share
it on the Hugging Face Hub.`),Cs.forEach(e),Qt=h(s),Sa=o(s,"P",{});var Ni=p(Sa);To=n(Ni,`As a final step of getting familiar with the data, explore it for potential issues. One common problem with datasets for
object detection is bounding boxes that \u201Cstretch\u201D beyond the edge of the image. Such \u201Crunaway\u201D bounding boxes can raise
errors during training and should be addressed at this stage. There are a few examples with this issue in this dataset.
To keep things simple in this guide, we remove these images from the data.`),Ni.forEach(e),Zt=h(s),d(Ws.$$.fragment,s),Xt=h(s),rs=o(s,"H2",{class:!0});var Zn=p(rs);bs=o(Zn,"A",{id:!0,class:!0,href:!0});var Gi=p(bs);Re=o(Gi,"SPAN",{});var Bi=p(Re);d(Js.$$.fragment,Bi),Bi.forEach(e),Gi.forEach(e),Co=h(Zn),He=o(Zn,"SPAN",{});var Ki=p(He);Oo=n(Ki,"Preprocess the data"),Ki.forEach(e),Zn.forEach(e),sn=h(s),C=o(s,"P",{});var ts=p(C);Po=n(ts,`To finetune a model, you must preprocess the data you plan to use to match precisely the approach used for the pre-trained model.
`),Ua=o(ts,"A",{href:!0});var Wi=p(Ua);Ao=n(Wi,"AutoImageProcessor"),Wi.forEach(e),Io=n(ts," takes care of processing image data to create "),Me=o(ts,"CODE",{});var Ji=p(Me);zo=n(Ji,"pixel_values"),Ji.forEach(e),Fo=n(ts,", "),Se=o(ts,"CODE",{});var Vi=p(Se);Lo=n(Vi,"pixel_mask"),Vi.forEach(e),Ro=n(ts,`, and
`),Ue=o(ts,"CODE",{});var Qi=p(Ue);Ho=n(Qi,"labels"),Qi.forEach(e),Mo=n(ts," that a DETR model can train with. The image processor has some attributes that you won\u2019t have to worry about:"),ts.forEach(e),an=h(s),_s=o(s,"UL",{});var Xn=p(_s);Ye=o(Xn,"LI",{});var Zi=p(Ye);Ne=o(Zi,"CODE",{});var Xi=p(Ne);So=n(Xi,"image_mean = [0.485, 0.456, 0.406 ]"),Xi.forEach(e),Zi.forEach(e),Uo=h(Xn),Ge=o(Xn,"LI",{});var sc=p(Ge);Be=o(sc,"CODE",{});var ac=p(Be);Yo=n(ac,"image_std = [0.229, 0.224, 0.225]"),ac.forEach(e),sc.forEach(e),Xn.forEach(e),en=h(s),Ya=o(s,"P",{});var ec=p(Ya);No=n(ec,`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.`),ec.forEach(e),tn=h(s),Na=o(s,"P",{});var tc=p(Na);Go=n(tc,"Instantiate the image processor from the same checkpoint as the model you want to finetune."),tc.forEach(e),nn=h(s),d(Vs.$$.fragment,s),ln=h(s),vs=o(s,"P",{});var sl=p(vs);Bo=n(sl,"Before passing the images to the "),Ke=o(sl,"CODE",{});var nc=p(Ke);Ko=n(nc,"image_processor"),nc.forEach(e),Wo=n(sl,", apply two preprocessing transformations to the dataset:"),sl.forEach(e),on=h(s),ws=o(s,"UL",{});var al=p(ws);We=o(al,"LI",{});var lc=p(We);Jo=n(lc,"Augmenting images"),lc.forEach(e),Vo=h(al),Je=o(al,"LI",{});var oc=p(Je);Qo=n(oc,"Reformatting annotations to meet DETR expectations"),oc.forEach(e),al.forEach(e),pn=h(s),Z=o(s,"P",{});var re=p(Z);Zo=n(re,"First, to make sure the model does not overfit on the training data, you can apply image augmentation with any data augmentation library. Here we use "),Qs=o(re,"A",{href:!0,rel:!0});var pc=p(Qs);Xo=n(pc,"Albumentations"),pc.forEach(e),sp=n(re,` \u2026
This library ensures that transformations affect the image and update the bounding boxes accordingly.
The \u{1F917} Datasets library documentation has a detailed `),Zs=o(re,"A",{href:!0,rel:!0});var rc=p(Zs);ap=n(rc,"guide on how to augment images for object detection"),rc.forEach(e),ep=n(re,`,
and it uses the exact same dataset as an example. Apply the same approach here, resize each image to (480, 480),
flip it horizontally, and brighten it:`),re.forEach(e),rn=h(s),d(Xs.$$.fragment,s),cn=h(s),X=o(s,"P",{});var ie=p(X);tp=n(ie,"The "),Ve=o(ie,"CODE",{});var ic=p(Ve);np=n(ic,"image_processor"),ic.forEach(e),lp=n(ie," expects the annotations to be in the following format: "),Qe=o(ie,"CODE",{});var cc=p(Qe);op=n(cc,"{'image_id': int, 'annotations': List[Dict]}"),cc.forEach(e),pp=n(ie,`,
where each dictionary is a COCO object annotation. Let\u2019s add a function to reformat annotations for a single example:`),ie.forEach(e),hn=h(s),d(sa.$$.fragment,s),mn=h(s),Ga=o(s,"P",{});var hc=p(Ga);rp=n(hc,"Now you can combine the image and annotation transformations to use on a batch of examples:"),hc.forEach(e),un=h(s),d(aa.$$.fragment,s),dn=h(s),ys=o(s,"P",{});var el=p(ys);ip=n(el,"Apply this preprocessing function to the entire dataset using \u{1F917} Datasets "),Ze=o(el,"CODE",{});var mc=p(Ze);cp=n(mc,"with_transform"),mc.forEach(e),hp=n(el,` method. This method applies
transformations on the fly when you load an element of the dataset.`),el.forEach(e),gn=h(s),z=o(s,"P",{});var Os=p(z);mp=n(Os,`At this point, you can check what an example from the dataset looks like after the transformations. You should see a tensor
with `),Xe=o(Os,"CODE",{});var uc=p(Xe);up=n(uc,"pixel_values"),uc.forEach(e),dp=n(Os,", a tensor with "),st=o(Os,"CODE",{});var dc=p(st);gp=n(dc,"pixel_mask"),dc.forEach(e),fp=n(Os,", and "),at=o(Os,"CODE",{});var gc=p(at);jp=n(gc,"labels"),gc.forEach(e),bp=n(Os,"."),Os.forEach(e),fn=h(s),d(ea.$$.fragment,s),jn=h(s),F=o(s,"P",{});var Ps=p(F);_p=n(Ps,`You have successfully augmented the individual images and prepared their annotations. However, preprocessing isn\u2019t
complete yet. In the final step, create a custom `),et=o(Ps,"CODE",{});var fc=p(et);vp=n(fc,"collate_fn"),fc.forEach(e),wp=n(Ps,` to batch images together.
Pad images (which are now `),tt=o(Ps,"CODE",{});var jc=p(tt);yp=n(jc,"pixel_values"),jc.forEach(e),xp=n(Ps,") to the largest image in a batch, and create a corresponding "),nt=o(Ps,"CODE",{});var bc=p(nt);qp=n(bc,"pixel_mask"),bc.forEach(e),Ep=n(Ps,`
to indicate which pixels are real (1) and which are padding (0).`),Ps.forEach(e),bn=h(s),d(ta.$$.fragment,s),_n=h(s),is=o(s,"H2",{class:!0});var tl=p(is);xs=o(tl,"A",{id:!0,class:!0,href:!0});var _c=p(xs);lt=o(_c,"SPAN",{});var vc=p(lt);d(na.$$.fragment,vc),vc.forEach(e),_c.forEach(e),kp=h(tl),ot=o(tl,"SPAN",{});var wc=p(ot);$p=n(wc,"Training the DETR model"),wc.forEach(e),tl.forEach(e),vn=n(s,`

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.
`),Ba=o(s,"P",{});var yc=p(Ba);Dp=n(yc,"Training involves the following steps:"),yc.forEach(e),wn=h(s),L=o(s,"OL",{});var As=p(L);la=o(As,"LI",{});var nl=p(la);Tp=n(nl,"Load the model with "),Ka=o(nl,"A",{href:!0});var xc=p(Ka);Cp=n(xc,"AutoModelForObjectDetection"),xc.forEach(e),Op=n(nl," using the same checkpoint as in the preprocessing."),nl.forEach(e),Pp=h(As),oa=o(As,"LI",{});var ll=p(oa);Ap=n(ll,"Define your training hyperparameters in "),Wa=o(ll,"A",{href:!0});var qc=p(Wa);Ip=n(qc,"TrainingArguments"),qc.forEach(e),zp=n(ll,"."),ll.forEach(e),Fp=h(As),pa=o(As,"LI",{});var ol=p(pa);Lp=n(ol,"Pass the training arguments to "),Ja=o(ol,"A",{href:!0});var Ec=p(Ja);Rp=n(Ec,"Trainer"),Ec.forEach(e),Hp=n(ol," along with the model, dataset, image processor, and data collator."),ol.forEach(e),Mp=h(As),ra=o(As,"LI",{});var pl=p(ra);Sp=n(pl,"Call "),Va=o(pl,"A",{href:!0});var kc=p(Va);Up=n(kc,"train()"),kc.forEach(e),Yp=n(pl," to finetune your model."),pl.forEach(e),As.forEach(e),yn=h(s),R=o(s,"P",{});var Is=p(R);Np=n(Is,"When loading the model from the same checkpoint that you used for the preprocessing, remember to pass the "),pt=o(Is,"CODE",{});var $c=p(pt);Gp=n($c,"label2id"),$c.forEach(e),Bp=n(Is,`
and `),rt=o(Is,"CODE",{});var Dc=p(rt);Kp=n(Dc,"id2label"),Dc.forEach(e),Wp=n(Is," maps that you created earlier from the dataset\u2019s metadata. Additionally, we specify "),it=o(Is,"CODE",{});var Tc=p(it);Jp=n(Tc,"ignore_mismatched_sizes=True"),Tc.forEach(e),Vp=n(Is," to replace the existing classification head with a new one."),Is.forEach(e),xn=h(s),d(ia.$$.fragment,s),qn=h(s),w=o(s,"P",{});var E=p(w);Qp=n(E,"In the "),Qa=o(E,"A",{href:!0});var Cc=p(Qa);Zp=n(Cc,"TrainingArguments"),Cc.forEach(e),Xp=n(E," use "),ct=o(E,"CODE",{});var Oc=p(ct);sr=n(Oc,"output_dir"),Oc.forEach(e),ar=n(E,` 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\u2019t create `),ht=o(E,"CODE",{});var Pc=p(ht);er=n(Pc,"pixel_values"),Pc.forEach(e),tr=n(E,". For this reason, set "),mt=o(E,"CODE",{});var Ac=p(mt);nr=n(Ac,"remove_unused_columns"),Ac.forEach(e),lr=n(E," to "),ut=o(E,"CODE",{});var Ic=p(ut);or=n(Ic,"False"),Ic.forEach(e),pr=n(E,`.
If you wish to share your model by pushing to the Hub, set `),dt=o(E,"CODE",{});var zc=p(dt);rr=n(zc,"push_to_hub"),zc.forEach(e),ir=n(E," to "),gt=o(E,"CODE",{});var Fc=p(gt);cr=n(Fc,"True"),Fc.forEach(e),hr=n(E,` (you must be signed in to Hugging
Face to upload your model).`),E.forEach(e),En=h(s),d(ca.$$.fragment,s),kn=h(s),qs=o(s,"P",{});var rl=p(qs);mr=n(rl,"Finally, bring everything together, and call "),Za=o(rl,"A",{href:!0});var Lc=p(Za);ur=n(Lc,"train()"),Lc.forEach(e),dr=n(rl,":"),rl.forEach(e),$n=h(s),d(ha.$$.fragment,s),Dn=h(s),O=o(s,"P",{});var ns=p(O);gr=n(ns,"If you have set "),ft=o(ns,"CODE",{});var Rc=p(ft);fr=n(Rc,"push_to_hub"),Rc.forEach(e),jr=n(ns," to "),jt=o(ns,"CODE",{});var Hc=p(jt);br=n(Hc,"True"),Hc.forEach(e),_r=n(ns," in the "),bt=o(ns,"CODE",{});var Mc=p(bt);vr=n(Mc,"training_args"),Mc.forEach(e),wr=n(ns,`, 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 `),Xa=o(ns,"A",{href:!0});var Sc=p(Xa);yr=n(Sc,"push_to_hub()"),Sc.forEach(e),xr=n(ns," method."),ns.forEach(e),Tn=h(s),d(ma.$$.fragment,s),Cn=h(s),cs=o(s,"H2",{class:!0});var il=p(cs);Es=o(il,"A",{id:!0,class:!0,href:!0});var Uc=p(Es);_t=o(Uc,"SPAN",{});var Yc=p(_t);d(ua.$$.fragment,Yc),Yc.forEach(e),Uc.forEach(e),qr=h(il),vt=o(il,"SPAN",{});var Nc=p(vt);Er=n(Nc,"Evaluate"),Nc.forEach(e),il.forEach(e),On=n(s,`

Object detection models are commonly evaluated with a set of `),da=o(s,"A",{href:!0});var Gc=p(da);kr=n(Gc,"COCO-style metrics"),Gc.forEach(e),Pn=n(s,`.
You can use one of the existing metrics implementations, but here you'll use the one from \`torchvision\` to evaluate the final
model that you pushed to the Hub.
`),ss=o(s,"P",{});var ce=p(ss);$r=n(ce,"To use the "),wt=o(ce,"CODE",{});var Bc=p(wt);Dr=n(Bc,"torchvision"),Bc.forEach(e),Tr=n(ce,` evaluator, you\u2019ll need to prepare a ground truth COCO dataset. The API to build a COCO dataset
requires the data to be stored in a certain format, so you\u2019ll need to save images and annotations to disk first. Just like
when you prepared your data for training, the annotations from the `),yt=o(ce,"CODE",{});var Kc=p(yt);Cr=n(Kc,'cppe5["test"]'),Kc.forEach(e),Or=n(ce,` need to be formatted. However, images
should stay as they are.`),ce.forEach(e),An=h(s),ks=o(s,"P",{});var cl=p(ks);Pr=n(cl,`The evaluation step requires a bit of work, but it can be split in three major steps.
First, prepare the `),xt=o(cl,"CODE",{});var Wc=p(xt);Ar=n(Wc,'cppe5["test"]'),Wc.forEach(e),Ir=n(cl," set: format the annotations and save the data to disk."),cl.forEach(e),In=h(s),d(ga.$$.fragment,s),zn=h(s),as=o(s,"P",{});var he=p(as);zr=n(he,"Next, prepare an instance of a "),qt=o(he,"CODE",{});var Jc=p(qt);Fr=n(Jc,"CocoDetection"),Jc.forEach(e),Lr=n(he," class that can be used with "),Et=o(he,"CODE",{});var Vc=p(Et);Rr=n(Vc,"cocoevaluator"),Vc.forEach(e),Hr=n(he,"."),he.forEach(e),Fn=h(s),d(fa.$$.fragment,s),Ln=h(s),se=o(s,"P",{});var Qc=p(se);Mr=n(Qc,"Finally, load the metrics and run the evaluation."),Qc.forEach(e),Rn=h(s),d(ja.$$.fragment,s),Hn=h(s),$s=o(s,"P",{});var hl=p($s);Sr=n(hl,"These results can be further improved by adjusting the hyperparameters in "),ae=o(hl,"A",{href:!0});var Zc=p(ae);Ur=n(Zc,"TrainingArguments"),Zc.forEach(e),Yr=n(hl,". Give it a go!"),hl.forEach(e),Mn=h(s),hs=o(s,"H2",{class:!0});var ml=p(hs);Ds=o(ml,"A",{id:!0,class:!0,href:!0});var Xc=p(Ds);kt=o(Xc,"SPAN",{});var sh=p(kt);d(ba.$$.fragment,sh),sh.forEach(e),Xc.forEach(e),Nr=h(ml),$t=o(ml,"SPAN",{});var ah=p($t);Gr=n(ah,"Inference"),ah.forEach(e),ml.forEach(e),Sn=n(s,`

Now that you have finetuned a DETR model, evaluated it, and uploaded it to the Hugging Face Hub, you can use it for inference.
The simplest way to try out your finetuned model for inference is to use it in a [Pipeline](/docs/transformers/v4.27.1/en/main_classes/pipelines#transformers.Pipeline). Instantiate a pipeline
for object detection with your model, and pass an image to it:

	`),d(_a.$$.fragment,s),Un=h(s),ee=o(s,"P",{});var eh=p(ee);Br=n(eh,"You can also manually replicate the results of the pipeline if you\u2019d like:"),eh.forEach(e),Yn=h(s),d(va.$$.fragment,s),Nn=h(s),te=o(s,"P",{});var th=p(te);Kr=n(th,"Let\u2019s plot the result:"),th.forEach(e),Gn=h(s),d(wa.$$.fragment,s),Bn=h(s),ya=o(s,"DIV",{class:!0});var nh=p(ya);ne=o(nh,"IMG",{src:!0,alt:!0}),nh.forEach(e),this.h()},h(){m($,"name","hf:doc:metadata"),m($,"content",JSON.stringify(gh)),m(P,"id","object-detection"),m(P,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(P,"href","#object-detection"),m(q,"class","relative group"),m(W,"href","https://huggingface.co/docs/transformers/model_doc/detr"),m(W,"rel","nofollow"),m(J,"href","https://huggingface.co/datasets/cppe-5"),m(J,"rel","nofollow"),m(ds,"id","load-the-cppe5-dataset"),m(ds,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(ds,"href","#load-the-cppe5-dataset"),m(ps,"class","relative group"),m(Ss,"href","https://huggingface.co/datasets/cppe-5"),m(Ss,"rel","nofollow"),m(Gs,"href","https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/#coco"),m(Gs,"rel","nofollow"),lh(Ma.src,Xr="https://i.imgur.com/TdaqPJO.png")||m(Ma,"src",Xr),m(Ma,"alt","CPPE-5 Image Example"),m(Ks,"class","flex justify-center"),m(bs,"id","preprocess-the-data"),m(bs,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(bs,"href","#preprocess-the-data"),m(rs,"class","relative group"),m(Ua,"href","/docs/transformers/v4.27.1/en/model_doc/auto#transformers.AutoImageProcessor"),m(Qs,"href","https://albumentations.ai/docs/"),m(Qs,"rel","nofollow"),m(Zs,"href","https://huggingface.co/docs/datasets/object_detection"),m(Zs,"rel","nofollow"),m(xs,"id","training-the-detr-model"),m(xs,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(xs,"href","#training-the-detr-model"),m(is,"class","relative group"),m(Ka,"href","/docs/transformers/v4.27.1/en/model_doc/auto#transformers.AutoModelForObjectDetection"),m(Wa,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.TrainingArguments"),m(Ja,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer"),m(Va,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer.train"),m(Qa,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.TrainingArguments"),m(Za,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer.train"),m(Xa,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.Trainer.push_to_hub"),m(Es,"id","evaluate"),m(Es,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Es,"href","#evaluate"),m(cs,"class","relative group"),m(da,"href","https://cocodataset.org/#detection-eval"),m(ae,"href","/docs/transformers/v4.27.1/en/main_classes/trainer#transformers.TrainingArguments"),m(Ds,"id","inference"),m(Ds,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),m(Ds,"href","#inference"),m(hs,"class","relative group"),lh(ne.src,si="https://i.imgur.com/4QZnf9A.png")||m(ne,"src",si),m(ne,"alt","Object detection result on a new image"),m(ya,"class","flex justify-center")},m(s,r){a(document.head,$),i(s,v,r),i(s,q,r),a(q,P),a(P,ls),g(D,ls,null),a(q,zs),a(q,os),a(os,G),i(s,ms,r),g(M,s,r),i(s,S,r),i(s,B,r),a(B,Fs),i(s,U,r),i(s,K,r),a(K,Ls),i(s,Y,r),i(s,A,r),a(A,x),a(x,y),a(x,W),a(W,qa),a(x,Ea),a(x,J),a(J,ka),a(x,$a),a(A,ul),a(A,ue),a(ue,dl),i(s,Ot,r),g(us,s,r),i(s,Pt,r),i(s,Da,r),a(Da,gl),i(s,At,r),g(Rs,s,r),i(s,It,r),i(s,V,r),a(V,fl),a(V,de),a(de,jl),a(V,bl),a(V,ge),a(ge,_l),a(V,vl),i(s,zt,r),i(s,Ta,r),a(Ta,wl),i(s,Ft,r),g(Hs,s,r),i(s,Lt,r),i(s,ps,r),a(ps,ds),a(ds,fe),g(Ms,fe,null),a(ps,yl),a(ps,je),a(je,xl),i(s,Rt,r),i(s,gs,r),a(gs,ql),a(gs,Ss),a(Ss,El),a(gs,kl),i(s,Ht,r),i(s,Ca,r),a(Ca,$l),i(s,Mt,r),g(Us,s,r),i(s,St,r),i(s,Oa,r),a(Oa,Dl),i(s,Ut,r),i(s,Pa,r),a(Pa,Tl),i(s,Yt,r),g(Ys,s,r),i(s,Nt,r),i(s,Aa,r),a(Aa,Cl),i(s,Gt,r),i(s,T,r),a(T,Ia),a(Ia,be),a(be,Ol),a(Ia,Pl),a(T,Al),a(T,fs),a(fs,_e),a(_e,Il),a(fs,zl),a(fs,ve),a(ve,Fl),a(fs,Ll),a(T,Rl),a(T,za),a(za,we),a(we,Hl),a(za,Ml),a(T,Sl),a(T,Fa),a(Fa,ye),a(ye,Ul),a(Fa,Yl),a(T,Nl),a(T,Ns),a(Ns,xe),a(xe,Gl),a(Ns,Bl),a(Ns,N),a(N,La),a(La,qe),a(qe,Kl),a(La,Wl),a(N,Jl),a(N,Ra),a(Ra,Ee),a(Ee,Vl),a(Ra,Ql),a(N,Zl),a(N,js),a(js,ke),a(ke,Xl),a(js,so),a(js,Gs),a(Gs,ao),a(js,eo),a(N,to),a(N,k),a(k,$e),a($e,no),a(k,lo),a(k,De),a(De,oo),a(k,po),a(k,Te),a(Te,ro),a(k,io),a(k,Ce),a(Ce,co),a(k,ho),a(k,Oe),a(Oe,mo),a(k,uo),a(k,Pe),a(Pe,go),i(s,Bt,r),i(s,Q,r),a(Q,fo),a(Q,Ae),a(Ae,jo),a(Q,bo),a(Q,Ie),a(Ie,_o),a(Q,vo),i(s,Kt,r),i(s,Ha,r),a(Ha,wo),i(s,Wt,r),g(Bs,s,r),i(s,Jt,r),i(s,Ks,r),a(Ks,Ma),i(s,Vt,r),i(s,I,r),a(I,yo),a(I,ze),a(ze,xo),a(I,qo),a(I,Fe),a(Fe,Eo),a(I,ko),a(I,Le),a(Le,$o),a(I,Do),i(s,Qt,r),i(s,Sa,r),a(Sa,To),i(s,Zt,r),g(Ws,s,r),i(s,Xt,r),i(s,rs,r),a(rs,bs),a(bs,Re),g(Js,Re,null),a(rs,Co),a(rs,He),a(He,Oo),i(s,sn,r),i(s,C,r),a(C,Po),a(C,Ua),a(Ua,Ao),a(C,Io),a(C,Me),a(Me,zo),a(C,Fo),a(C,Se),a(Se,Lo),a(C,Ro),a(C,Ue),a(Ue,Ho),a(C,Mo),i(s,an,r),i(s,_s,r),a(_s,Ye),a(Ye,Ne),a(Ne,So),a(_s,Uo),a(_s,Ge),a(Ge,Be),a(Be,Yo),i(s,en,r),i(s,Ya,r),a(Ya,No),i(s,tn,r),i(s,Na,r),a(Na,Go),i(s,nn,r),g(Vs,s,r),i(s,ln,r),i(s,vs,r),a(vs,Bo),a(vs,Ke),a(Ke,Ko),a(vs,Wo),i(s,on,r),i(s,ws,r),a(ws,We),a(We,Jo),a(ws,Vo),a(ws,Je),a(Je,Qo),i(s,pn,r),i(s,Z,r),a(Z,Zo),a(Z,Qs),a(Qs,Xo),a(Z,sp),a(Z,Zs),a(Zs,ap),a(Z,ep),i(s,rn,r),g(Xs,s,r),i(s,cn,r),i(s,X,r),a(X,tp),a(X,Ve),a(Ve,np),a(X,lp),a(X,Qe),a(Qe,op),a(X,pp),i(s,hn,r),g(sa,s,r),i(s,mn,r),i(s,Ga,r),a(Ga,rp),i(s,un,r),g(aa,s,r),i(s,dn,r),i(s,ys,r),a(ys,ip),a(ys,Ze),a(Ze,cp),a(ys,hp),i(s,gn,r),i(s,z,r),a(z,mp),a(z,Xe),a(Xe,up),a(z,dp),a(z,st),a(st,gp),a(z,fp),a(z,at),a(at,jp),a(z,bp),i(s,fn,r),g(ea,s,r),i(s,jn,r),i(s,F,r),a(F,_p),a(F,et),a(et,vp),a(F,wp),a(F,tt),a(tt,yp),a(F,xp),a(F,nt),a(nt,qp),a(F,Ep),i(s,bn,r),g(ta,s,r),i(s,_n,r),i(s,is,r),a(is,xs),a(xs,lt),g(na,lt,null),a(is,kp),a(is,ot),a(ot,$p),i(s,vn,r),i(s,Ba,r),a(Ba,Dp),i(s,wn,r),i(s,L,r),a(L,la),a(la,Tp),a(la,Ka),a(Ka,Cp),a(la,Op),a(L,Pp),a(L,oa),a(oa,Ap),a(oa,Wa),a(Wa,Ip),a(oa,zp),a(L,Fp),a(L,pa),a(pa,Lp),a(pa,Ja),a(Ja,Rp),a(pa,Hp),a(L,Mp),a(L,ra),a(ra,Sp),a(ra,Va),a(Va,Up),a(ra,Yp),i(s,yn,r),i(s,R,r),a(R,Np),a(R,pt),a(pt,Gp),a(R,Bp),a(R,rt),a(rt,Kp),a(R,Wp),a(R,it),a(it,Jp),a(R,Vp),i(s,xn,r),g(ia,s,r),i(s,qn,r),i(s,w,r),a(w,Qp),a(w,Qa),a(Qa,Zp),a(w,Xp),a(w,ct),a(ct,sr),a(w,ar),a(w,ht),a(ht,er),a(w,tr),a(w,mt),a(mt,nr),a(w,lr),a(w,ut),a(ut,or),a(w,pr),a(w,dt),a(dt,rr),a(w,ir),a(w,gt),a(gt,cr),a(w,hr),i(s,En,r),g(ca,s,r),i(s,kn,r),i(s,qs,r),a(qs,mr),a(qs,Za),a(Za,ur),a(qs,dr),i(s,$n,r),g(ha,s,r),i(s,Dn,r),i(s,O,r),a(O,gr),a(O,ft),a(ft,fr),a(O,jr),a(O,jt),a(jt,br),a(O,_r),a(O,bt),a(bt,vr),a(O,wr),a(O,Xa),a(Xa,yr),a(O,xr),i(s,Tn,r),g(ma,s,r),i(s,Cn,r),i(s,cs,r),a(cs,Es),a(Es,_t),g(ua,_t,null),a(cs,qr),a(cs,vt),a(vt,Er),i(s,On,r),i(s,da,r),a(da,kr),i(s,Pn,r),i(s,ss,r),a(ss,$r),a(ss,wt),a(wt,Dr),a(ss,Tr),a(ss,yt),a(yt,Cr),a(ss,Or),i(s,An,r),i(s,ks,r),a(ks,Pr),a(ks,xt),a(xt,Ar),a(ks,Ir),i(s,In,r),g(ga,s,r),i(s,zn,r),i(s,as,r),a(as,zr),a(as,qt),a(qt,Fr),a(as,Lr),a(as,Et),a(Et,Rr),a(as,Hr),i(s,Fn,r),g(fa,s,r),i(s,Ln,r),i(s,se,r),a(se,Mr),i(s,Rn,r),g(ja,s,r),i(s,Hn,r),i(s,$s,r),a($s,Sr),a($s,ae),a(ae,Ur),a($s,Yr),i(s,Mn,r),i(s,hs,r),a(hs,Ds),a(Ds,kt),g(ba,kt,null),a(hs,Nr),a(hs,$t),a($t,Gr),i(s,Sn,r),g(_a,s,r),i(s,Un,r),i(s,ee,r),a(ee,Br),i(s,Yn,r),g(va,s,r),i(s,Nn,r),i(s,te,r),a(te,Kr),i(s,Gn,r),g(wa,s,r),i(s,Bn,r),i(s,ya,r),a(ya,ne),Kn=!0},p(s,[r]){const xa={};r&2&&(xa.$$scope={dirty:r,ctx:s}),us.$set(xa)},i(s){Kn||(f(D.$$.fragment,s),f(M.$$.fragment,s),f(us.$$.fragment,s),f(Rs.$$.fragment,s),f(Hs.$$.fragment,s),f(Ms.$$.fragment,s),f(Us.$$.fragment,s),f(Ys.$$.fragment,s),f(Bs.$$.fragment,s),f(Ws.$$.fragment,s),f(Js.$$.fragment,s),f(Vs.$$.fragment,s),f(Xs.$$.fragment,s),f(sa.$$.fragment,s),f(aa.$$.fragment,s),f(ea.$$.fragment,s),f(ta.$$.fragment,s),f(na.$$.fragment,s),f(ia.$$.fragment,s),f(ca.$$.fragment,s),f(ha.$$.fragment,s),f(ma.$$.fragment,s),f(ua.$$.fragment,s),f(ga.$$.fragment,s),f(fa.$$.fragment,s),f(ja.$$.fragment,s),f(ba.$$.fragment,s),f(_a.$$.fragment,s),f(va.$$.fragment,s),f(wa.$$.fragment,s),Kn=!0)},o(s){j(D.$$.fragment,s),j(M.$$.fragment,s),j(us.$$.fragment,s),j(Rs.$$.fragment,s),j(Hs.$$.fragment,s),j(Ms.$$.fragment,s),j(Us.$$.fragment,s),j(Ys.$$.fragment,s),j(Bs.$$.fragment,s),j(Ws.$$.fragment,s),j(Js.$$.fragment,s),j(Vs.$$.fragment,s),j(Xs.$$.fragment,s),j(sa.$$.fragment,s),j(aa.$$.fragment,s),j(ea.$$.fragment,s),j(ta.$$.fragment,s),j(na.$$.fragment,s),j(ia.$$.fragment,s),j(ca.$$.fragment,s),j(ha.$$.fragment,s),j(ma.$$.fragment,s),j(ua.$$.fragment,s),j(ga.$$.fragment,s),j(fa.$$.fragment,s),j(ja.$$.fragment,s),j(ba.$$.fragment,s),j(_a.$$.fragment,s),j(va.$$.fragment,s),j(wa.$$.fragment,s),Kn=!1},d(s){e($),s&&e(v),s&&e(q),b(D),s&&e(ms),b(M,s),s&&e(S),s&&e(B),s&&e(U),s&&e(K),s&&e(Y),s&&e(A),s&&e(Ot),b(us,s),s&&e(Pt),s&&e(Da),s&&e(At),b(Rs,s),s&&e(It),s&&e(V),s&&e(zt),s&&e(Ta),s&&e(Ft),b(Hs,s),s&&e(Lt),s&&e(ps),b(Ms),s&&e(Rt),s&&e(gs),s&&e(Ht),s&&e(Ca),s&&e(Mt),b(Us,s),s&&e(St),s&&e(Oa),s&&e(Ut),s&&e(Pa),s&&e(Yt),b(Ys,s),s&&e(Nt),s&&e(Aa),s&&e(Gt),s&&e(T),s&&e(Bt),s&&e(Q),s&&e(Kt),s&&e(Ha),s&&e(Wt),b(Bs,s),s&&e(Jt),s&&e(Ks),s&&e(Vt),s&&e(I),s&&e(Qt),s&&e(Sa),s&&e(Zt),b(Ws,s),s&&e(Xt),s&&e(rs),b(Js),s&&e(sn),s&&e(C),s&&e(an),s&&e(_s),s&&e(en),s&&e(Ya),s&&e(tn),s&&e(Na),s&&e(nn),b(Vs,s),s&&e(ln),s&&e(vs),s&&e(on),s&&e(ws),s&&e(pn),s&&e(Z),s&&e(rn),b(Xs,s),s&&e(cn),s&&e(X),s&&e(hn),b(sa,s),s&&e(mn),s&&e(Ga),s&&e(un),b(aa,s),s&&e(dn),s&&e(ys),s&&e(gn),s&&e(z),s&&e(fn),b(ea,s),s&&e(jn),s&&e(F),s&&e(bn),b(ta,s),s&&e(_n),s&&e(is),b(na),s&&e(vn),s&&e(Ba),s&&e(wn),s&&e(L),s&&e(yn),s&&e(R),s&&e(xn),b(ia,s),s&&e(qn),s&&e(w),s&&e(En),b(ca,s),s&&e(kn),s&&e(qs),s&&e($n),b(ha,s),s&&e(Dn),s&&e(O),s&&e(Tn),b(ma,s),s&&e(Cn),s&&e(cs),b(ua),s&&e(On),s&&e(da),s&&e(Pn),s&&e(ss),s&&e(An),s&&e(ks),s&&e(In),b(ga,s),s&&e(zn),s&&e(as),s&&e(Fn),b(fa,s),s&&e(Ln),s&&e(se),s&&e(Rn),b(ja,s),s&&e(Hn),s&&e($s),s&&e(Mn),s&&e(hs),b(ba),s&&e(Sn),b(_a,s),s&&e(Un),s&&e(ee),s&&e(Yn),b(va,s),s&&e(Nn),s&&e(te),s&&e(Gn),b(wa,s),s&&e(Bn),s&&e(ya)}}}const gh={local:"object-detection",sections:[{local:"load-the-cppe5-dataset",title:"Load the CPPE-5 dataset"},{local:"preprocess-the-data",title:"Preprocess the data"},{local:"training-the-detr-model",title:"Training the DETR model"},{local:"evaluate",title:"Evaluate"},{local:"inference",title:"Inference"}],title:"Object detection"};function fh(Ct){return ch(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class yh extends oh{constructor($){super();ph(this,$,fh,dh,rh,{})}}export{yh as default,gh as metadata};
