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 ue}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,O;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"),O=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 Ea=p(D);zs=n(Ea,"Deformable DETR"),Ea.forEach(e),os=n(y,", "),G=o(y,"A",{href:!0});var ka=p(G);ms=n(ka,"DETA"),ka.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 $a=p(U);K=n($a,"Table Transformer"),$a.forEach(e),Ls=n(y,", "),Y=o(y,"A",{href:!0});var Da=p(Y);O=n(Da,"YOLOS"),Da.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,O)},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,O,x,y,W,Ea,ka,J,$a,Da,ul,de,dl,At,us,Pt,Ta,gl,Ot,Rs,It,V,fl,ge,jl,bl,fe,_l,vl,zt,Ca,wl,Ft,Hs,Lt,ps,ds,je,Ms,yl,be,xl,Rt,gs,ql,Ss,El,kl,Ht,Aa,$l,Mt,Us,St,Pa,Dl,Ut,Oa,Tl,Yt,Ys,Nt,Ia,Cl,Gt,T,za,_e,Al,Pl,Ol,fs,ve,Il,zl,we,Fl,Ll,Rl,Fa,ye,Hl,Ml,Sl,La,xe,Ul,Yl,Nl,Ns,qe,Gl,Bl,N,Ra,Ee,Kl,Wl,Jl,Ha,ke,Vl,Ql,Zl,js,$e,Xl,so,Gs,ao,eo,to,k,De,no,lo,Te,oo,po,Ce,ro,io,Ae,co,ho,Pe,mo,uo,Oe,go,Bt,Q,fo,Ie,jo,bo,ze,_o,vo,Kt,Ma,wo,Wt,Bs,Jt,Ks,Sa,Xr,Vt,I,yo,Fe,xo,qo,Le,Eo,ko,Re,$o,Do,Qt,Ua,To,Zt,Ws,Xt,rs,bs,He,Js,Co,Me,Ao,sn,C,Po,Ya,Oo,Io,Se,zo,Fo,Ue,Lo,Ro,Ye,Ho,Mo,an,_s,Ne,Ge,So,Uo,Be,Ke,Yo,en,Na,No,tn,Ga,Go,nn,Vs,ln,vs,Bo,We,Ko,Wo,on,ws,Je,Jo,Vo,Ve,Qo,pn,Z,Zo,Qs,Xo,sp,Zs,ap,ep,rn,Xs,cn,X,tp,Qe,np,lp,Ze,op,pp,hn,sa,mn,Ba,rp,un,aa,dn,ys,ip,ea,cp,hp,gn,z,mp,Xe,up,dp,st,gp,fp,at,jp,bp,fn,ta,jn,F,_p,et,vp,wp,tt,yp,xp,nt,qp,Ep,bn,na,_n,is,xs,lt,la,kp,ot,$p,vn,Ka,Dp,wn,L,oa,Tp,Wa,Cp,Ap,Pp,pa,Op,Ja,Ip,zp,Fp,ra,Lp,Va,Rp,Hp,Mp,ia,Sp,Qa,Up,Yp,yn,R,Np,pt,Gp,Bp,rt,Kp,Wp,it,Jp,Vp,xn,ca,qn,w,Qp,Za,Zp,Xp,ct,sr,ar,ht,er,tr,mt,nr,lr,ut,or,pr,dt,rr,ir,gt,cr,hr,En,ha,kn,qs,mr,Xa,ur,dr,$n,ma,Dn,A,gr,ft,fr,jr,jt,br,_r,bt,vr,wr,se,yr,xr,Tn,ua,Cn,cs,Es,_t,da,qr,vt,Er,An,ga,kr,Pn,ss,$r,wt,Dr,Tr,yt,Cr,Ar,On,ks,Pr,xt,Or,Ir,In,fa,zn,as,zr,qt,Fr,Lr,Et,Rr,Hr,Fn,ja,Ln,ae,Mr,Rn,ba,Hn,$s,Sr,ee,Ur,Yr,Mn,hs,Ds,kt,_a,Nr,$t,Gr,Sn,va,Un,te,Br,Yn,wa,Nn,ne,Kr,Gn,ya,Bn,xa,le,si,Kn;return D=new ue({}),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 ue({}),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 ue({}),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>)`}}),ta=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>])}}`}}),na=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`}}),la=new ue({}),ca=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>)`}}),ha=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>)`}}),ma=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()`}}),ua=new _({props:{code:"trainer.push_to_hub()",highlighted:'<span class="hljs-meta">&gt;&gt;&gt; </span>trainer.push_to_hub()'}}),da=new ue({}),fa=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`}}),ja=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)`}}),ba=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>`}}),_a=new ue({}),va=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)`}}),wa=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>]`}}),ya=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(),O=l("ol"),x=l("li"),y=t("Finetune "),W=l("a"),Ea=t("DETR"),ka=t(`, a model that combines a convolutional
backbone with an encoder-decoder Transformer, on the `),J=l("a"),$a=t("CPPE-5"),Da=t(`
dataset.`),ul=c(),de=l("li"),dl=t("Use your finetuned model for inference."),At=c(),u(us.$$.fragment),Pt=c(),Ta=l("p"),gl=t("Before you begin, make sure you have all the necessary libraries installed:"),Ot=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 `),ge=l("code"),jl=t("albumentations"),bl=t(" to augment the data. "),fe=l("code"),_l=t("timm"),vl=t(" is currently required to load a convolutional backbone for the DETR model."),zt=c(),Ca=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"),je=l("span"),u(Ms.$$.fragment),yl=c(),be=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(),Aa=l("p"),$l=t("Start by loading the dataset:"),Mt=c(),u(Us.$$.fragment),St=c(),Pa=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(),Oa=l("p"),Tl=t("To get familiar with the data, explore what the examples look like."),Yt=c(),u(Ys.$$.fragment),Nt=c(),Ia=l("p"),Cl=t("The examples in the dataset have the following fields:"),Gt=c(),T=l("ul"),za=l("li"),_e=l("code"),Al=t("image_id"),Pl=t(": the example image id"),Ol=c(),fs=l("li"),ve=l("code"),Il=t("image"),zl=t(": a "),we=l("code"),Fl=t("PIL.Image.Image"),Ll=t(" object containing the image"),Rl=c(),Fa=l("li"),ye=l("code"),Hl=t("width"),Ml=t(": width of the image"),Sl=c(),La=l("li"),xe=l("code"),Ul=t("height"),Yl=t(": height of the image"),Nl=c(),Ns=l("li"),qe=l("code"),Gl=t("objects"),Bl=t(": a dictionary containing bounding box metadata for the objects in the image:"),N=l("ul"),Ra=l("li"),Ee=l("code"),Kl=t("id"),Wl=t(": the annotation id"),Jl=c(),Ha=l("li"),ke=l("code"),Vl=t("area"),Ql=t(": the area of the bounding box"),Zl=c(),js=l("li"),$e=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"),De=l("code"),no=t("category"),lo=t(": the object\u2019s category, with possible values including "),Te=l("code"),oo=t("Coverall (0)"),po=t(", "),Ce=l("code"),ro=t("Face_Shield (1)"),io=t(", "),Ae=l("code"),co=t("Gloves (2)"),ho=t(", "),Pe=l("code"),mo=t("Goggles (3)"),uo=t(" and "),Oe=l("code"),go=t("Mask (4)"),Bt=c(),Q=l("p"),fo=t("You may notice that the "),Ie=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 `),ze=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(),Ma=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"),Sa=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 `),Fe=l("code"),xo=t("category"),qo=t(` field.
You\u2019ll also want to create dictionaries that map a label id to a label class (`),Le=l("code"),Eo=t("id2label"),ko=t(") and the other way around ("),Re=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(),Ua=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"),He=l("span"),u(Js.$$.fragment),Co=c(),Me=l("span"),Ao=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.
`),Ya=l("a"),Oo=t("AutoImageProcessor"),Io=t(" takes care of processing image data to create "),Se=l("code"),zo=t("pixel_values"),Fo=t(", "),Ue=l("code"),Lo=t("pixel_mask"),Ro=t(`, and
`),Ye=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"),Ne=l("li"),Ge=l("code"),So=t("image_mean = [0.485, 0.456, 0.406 ]"),Uo=c(),Be=l("li"),Ke=l("code"),Yo=t("image_std = [0.229, 0.224, 0.225]"),en=c(),Na=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(),Ga=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 "),We=l("code"),Ko=t("image_processor"),Wo=t(", apply two preprocessing transformations to the dataset:"),on=c(),ws=l("ul"),Je=l("li"),Jo=t("Augmenting images"),Vo=c(),Ve=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 "),Qe=l("code"),np=t("image_processor"),lp=t(" expects the annotations to be in the following format: "),Ze=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(),Ba=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 "),ea=l("a"),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(ta.$$.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(na.$$.fragment),_n=c(),is=l("h2"),xs=l("a"),lt=l("span"),u(la.$$.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.
`),Ka=l("p"),Dp=t("Training involves the following steps:"),wn=c(),L=l("ol"),oa=l("li"),Tp=t("Load the model with "),Wa=l("a"),Cp=t("AutoModelForObjectDetection"),Ap=t(" using the same checkpoint as in the preprocessing."),Pp=c(),pa=l("li"),Op=t("Define your training hyperparameters in "),Ja=l("a"),Ip=t("TrainingArguments"),zp=t("."),Fp=c(),ra=l("li"),Lp=t("Pass the training arguments to "),Va=l("a"),Rp=t("Trainer"),Hp=t(" along with the model, dataset, image processor, and data collator."),Mp=c(),ia=l("li"),Sp=t("Call "),Qa=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(ca.$$.fragment),qn=c(),w=l("p"),Qp=t("In the "),Za=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(ha.$$.fragment),kn=c(),qs=l("p"),mr=t("Finally, bring everything together, and call "),Xa=l("a"),ur=t("train()"),dr=t(":"),$n=c(),u(ma.$$.fragment),Dn=c(),A=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 `),se=l("a"),yr=t("push_to_hub()"),xr=t(" method."),Tn=c(),u(ua.$$.fragment),Cn=c(),cs=l("h2"),Es=l("a"),_t=l("span"),u(da.$$.fragment),qr=c(),vt=l("span"),Er=t("Evaluate"),An=t(`

Object detection models are commonly evaluated with a set of `),ga=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"]'),Ar=t(` need to be formatted. However, images
should stay as they are.`),On=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"),Or=t('cppe5["test"]'),Ir=t(" set: format the annotations and save the data to disk."),In=c(),u(fa.$$.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(ja.$$.fragment),Ln=c(),ae=l("p"),Mr=t("Finally, load the metrics and run the evaluation."),Rn=c(),u(ba.$$.fragment),Hn=c(),$s=l("p"),Sr=t("These results can be further improved by adjusting the hyperparameters in "),ee=l("a"),Ur=t("TrainingArguments"),Yr=t(". Give it a go!"),Mn=c(),hs=l("h2"),Ds=l("a"),kt=l("span"),u(_a.$$.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.29.0/en/main_classes/pipelines#transformers.Pipeline). Instantiate a pipeline
for object detection with your model, and pass an image to it:

	`),u(va.$$.fragment),Un=c(),te=l("p"),Br=t("You can also manually replicate the results of the pipeline if you\u2019d like:"),Yn=c(),u(wa.$$.fragment),Nn=c(),ne=l("p"),Kr=t("Let\u2019s plot the result:"),Gn=c(),u(ya.$$.fragment),Bn=c(),xa=l("div"),le=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 qa=p(q);P=o(qa,"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(qa),os=o(qa,"SPAN",{});var ti=p(os);G=n(ti,"Object detection"),ti.forEach(e),qa.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),O=o(s,"OL",{});var Wn=p(O);x=o(Wn,"LI",{});var oe=p(x);y=n(oe,"Finetune "),W=o(oe,"A",{href:!0,rel:!0});var oi=p(W);Ea=n(oi,"DETR"),oi.forEach(e),ka=n(oe,`, a model that combines a convolutional
backbone with an encoder-decoder Transformer, on the `),J=o(oe,"A",{href:!0,rel:!0});var pi=p(J);$a=n(pi,"CPPE-5"),pi.forEach(e),Da=n(oe,`
dataset.`),oe.forEach(e),ul=h(Wn),de=o(Wn,"LI",{});var ri=p(de);dl=n(ri,"Use your finetuned model for inference."),ri.forEach(e),Wn.forEach(e),At=h(s),d(us.$$.fragment,s),Pt=h(s),Ta=o(s,"P",{});var ii=p(Ta);gl=n(ii,"Before you begin, make sure you have all the necessary libraries installed:"),ii.forEach(e),Ot=h(s),d(Rs.$$.fragment,s),It=h(s),V=o(s,"P",{});var pe=p(V);fl=n(pe,`You\u2019ll use \u{1F917} Datasets to load a dataset from the Hugging Face Hub, \u{1F917} Transformers to train your model,
and `),ge=o(pe,"CODE",{});var ci=p(ge);jl=n(ci,"albumentations"),ci.forEach(e),bl=n(pe," to augment the data. "),fe=o(pe,"CODE",{});var hi=p(fe);_l=n(hi,"timm"),hi.forEach(e),vl=n(pe," is currently required to load a convolutional backbone for the DETR model."),pe.forEach(e),zt=h(s),Ca=o(s,"P",{});var mi=p(Ca);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);je=o(ui,"SPAN",{});var di=p(je);d(Ms.$$.fragment,di),di.forEach(e),ui.forEach(e),yl=h(Jn),be=o(Jn,"SPAN",{});var gi=p(be);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),Aa=o(s,"P",{});var ji=p(Aa);$l=n(ji,"Start by loading the dataset:"),ji.forEach(e),Mt=h(s),d(Us.$$.fragment,s),St=h(s),Pa=o(s,"P",{});var bi=p(Pa);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),Oa=o(s,"P",{});var _i=p(Oa);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),Ia=o(s,"P",{});var vi=p(Ia);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);za=o(es,"LI",{});var Wr=p(za);_e=o(Wr,"CODE",{});var wi=p(_e);Al=n(wi,"image_id"),wi.forEach(e),Pl=n(Wr,": the example image id"),Wr.forEach(e),Ol=h(es),fs=o(es,"LI",{});var Dt=p(fs);ve=o(Dt,"CODE",{});var yi=p(ve);Il=n(yi,"image"),yi.forEach(e),zl=n(Dt,": a "),we=o(Dt,"CODE",{});var xi=p(we);Fl=n(xi,"PIL.Image.Image"),xi.forEach(e),Ll=n(Dt," object containing the image"),Dt.forEach(e),Rl=h(es),Fa=o(es,"LI",{});var Jr=p(Fa);ye=o(Jr,"CODE",{});var qi=p(ye);Hl=n(qi,"width"),qi.forEach(e),Ml=n(Jr,": width of the image"),Jr.forEach(e),Sl=h(es),La=o(es,"LI",{});var Vr=p(La);xe=o(Vr,"CODE",{});var Ei=p(xe);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);qe=o(Qn,"CODE",{});var ki=p(qe);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);Ra=o(Ts,"LI",{});var Qr=p(Ra);Ee=o(Qr,"CODE",{});var $i=p(Ee);Kl=n($i,"id"),$i.forEach(e),Wl=n(Qr,": the annotation id"),Qr.forEach(e),Jl=h(Ts),Ha=o(Ts,"LI",{});var Zr=p(Ha);ke=o(Zr,"CODE",{});var Di=p(ke);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);$e=o(Tt,"CODE",{});var Ti=p($e);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);De=o(H,"CODE",{});var Ai=p(De);no=n(Ai,"category"),Ai.forEach(e),lo=n(H,": the object\u2019s category, with possible values including "),Te=o(H,"CODE",{});var Pi=p(Te);oo=n(Pi,"Coverall (0)"),Pi.forEach(e),po=n(H,", "),Ce=o(H,"CODE",{});var Oi=p(Ce);ro=n(Oi,"Face_Shield (1)"),Oi.forEach(e),io=n(H,", "),Ae=o(H,"CODE",{});var Ii=p(Ae);co=n(Ii,"Gloves (2)"),Ii.forEach(e),ho=n(H,", "),Pe=o(H,"CODE",{});var zi=p(Pe);mo=n(zi,"Goggles (3)"),zi.forEach(e),uo=n(H," and "),Oe=o(H,"CODE",{});var Fi=p(Oe);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 re=p(Q);fo=n(re,"You may notice that the "),Ie=o(re,"CODE",{});var Li=p(Ie);jo=n(Li,"bbox"),Li.forEach(e),bo=n(re,` field follows the COCO format, which is the format that the DETR model expects.
However, the grouping of the fields inside `),ze=o(re,"CODE",{});var Ri=p(ze);_o=n(Ri,"objects"),Ri.forEach(e),vo=n(re,` differs from the annotation format DETR requires. You will
need to apply some preprocessing transformations before using this data for training.`),re.forEach(e),Kt=h(s),Ma=o(s,"P",{});var Hi=p(Ma);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);Sa=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 `),Fe=o(Cs,"CODE",{});var Si=p(Fe);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 (`),Le=o(Cs,"CODE",{});var Ui=p(Le);Eo=n(Ui,"id2label"),Ui.forEach(e),ko=n(Cs,") and the other way around ("),Re=o(Cs,"CODE",{});var Yi=p(Re);$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),Ua=o(s,"P",{});var Ni=p(Ua);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);He=o(Gi,"SPAN",{});var Bi=p(He);d(Js.$$.fragment,Bi),Bi.forEach(e),Gi.forEach(e),Co=h(Zn),Me=o(Zn,"SPAN",{});var Ki=p(Me);Ao=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.
`),Ya=o(ts,"A",{href:!0});var Wi=p(Ya);Oo=n(Wi,"AutoImageProcessor"),Wi.forEach(e),Io=n(ts," takes care of processing image data to create "),Se=o(ts,"CODE",{});var Ji=p(Se);zo=n(Ji,"pixel_values"),Ji.forEach(e),Fo=n(ts,", "),Ue=o(ts,"CODE",{});var Vi=p(Ue);Lo=n(Vi,"pixel_mask"),Vi.forEach(e),Ro=n(ts,`, and
`),Ye=o(ts,"CODE",{});var Qi=p(Ye);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);Ne=o(Xn,"LI",{});var Zi=p(Ne);Ge=o(Zi,"CODE",{});var Xi=p(Ge);So=n(Xi,"image_mean = [0.485, 0.456, 0.406 ]"),Xi.forEach(e),Zi.forEach(e),Uo=h(Xn),Be=o(Xn,"LI",{});var sc=p(Be);Ke=o(sc,"CODE",{});var ac=p(Ke);Yo=n(ac,"image_std = [0.229, 0.224, 0.225]"),ac.forEach(e),sc.forEach(e),Xn.forEach(e),en=h(s),Na=o(s,"P",{});var ec=p(Na);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),Ga=o(s,"P",{});var tc=p(Ga);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 "),We=o(sl,"CODE",{});var nc=p(We);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);Je=o(al,"LI",{});var lc=p(Je);Jo=n(lc,"Augmenting images"),lc.forEach(e),Vo=h(al),Ve=o(al,"LI",{});var oc=p(Ve);Qo=n(oc,"Reformatting annotations to meet DETR expectations"),oc.forEach(e),al.forEach(e),pn=h(s),Z=o(s,"P",{});var ie=p(Z);Zo=n(ie,"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(ie,"A",{href:!0,rel:!0});var pc=p(Qs);Xo=n(pc,"Albumentations"),pc.forEach(e),sp=n(ie,` \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(ie,"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(ie,`,
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:`),ie.forEach(e),rn=h(s),d(Xs.$$.fragment,s),cn=h(s),X=o(s,"P",{});var ce=p(X);tp=n(ce,"The "),Qe=o(ce,"CODE",{});var ic=p(Qe);np=n(ic,"image_processor"),ic.forEach(e),lp=n(ce," expects the annotations to be in the following format: "),Ze=o(ce,"CODE",{});var cc=p(Ze);op=n(cc,"{'image_id': int, 'annotations': List[Dict]}"),cc.forEach(e),pp=n(ce,`,
where each dictionary is a COCO object annotation. Let\u2019s add a function to reformat annotations for a single example:`),ce.forEach(e),hn=h(s),d(sa.$$.fragment,s),mn=h(s),Ba=o(s,"P",{});var hc=p(Ba);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 "),ea=o(el,"A",{href:!0,rel:!0});var mc=p(ea);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 As=p(z);mp=n(As,`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(As,"CODE",{});var uc=p(Xe);up=n(uc,"pixel_values"),uc.forEach(e),dp=n(As,", a tensor with "),st=o(As,"CODE",{});var dc=p(st);gp=n(dc,"pixel_mask"),dc.forEach(e),fp=n(As,", and "),at=o(As,"CODE",{});var gc=p(at);jp=n(gc,"labels"),gc.forEach(e),bp=n(As,"."),As.forEach(e),fn=h(s),d(ta.$$.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(na.$$.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(la.$$.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.
`),Ka=o(s,"P",{});var yc=p(Ka);Dp=n(yc,"Training involves the following steps:"),yc.forEach(e),wn=h(s),L=o(s,"OL",{});var Os=p(L);oa=o(Os,"LI",{});var nl=p(oa);Tp=n(nl,"Load the model with "),Wa=o(nl,"A",{href:!0});var xc=p(Wa);Cp=n(xc,"AutoModelForObjectDetection"),xc.forEach(e),Ap=n(nl," using the same checkpoint as in the preprocessing."),nl.forEach(e),Pp=h(Os),pa=o(Os,"LI",{});var ll=p(pa);Op=n(ll,"Define your training hyperparameters in "),Ja=o(ll,"A",{href:!0});var qc=p(Ja);Ip=n(qc,"TrainingArguments"),qc.forEach(e),zp=n(ll,"."),ll.forEach(e),Fp=h(Os),ra=o(Os,"LI",{});var ol=p(ra);Lp=n(ol,"Pass the training arguments to "),Va=o(ol,"A",{href:!0});var Ec=p(Va);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(Os),ia=o(Os,"LI",{});var pl=p(ia);Sp=n(pl,"Call "),Qa=o(pl,"A",{href:!0});var kc=p(Qa);Up=n(kc,"train()"),kc.forEach(e),Yp=n(pl," to finetune your model."),pl.forEach(e),Os.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(ca.$$.fragment,s),qn=h(s),w=o(s,"P",{});var E=p(w);Qp=n(E,"In the "),Za=o(E,"A",{href:!0});var Cc=p(Za);Zp=n(Cc,"TrainingArguments"),Cc.forEach(e),Xp=n(E," use "),ct=o(E,"CODE",{});var Ac=p(ct);sr=n(Ac,"output_dir"),Ac.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 Oc=p(mt);nr=n(Oc,"remove_unused_columns"),Oc.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(ha.$$.fragment,s),kn=h(s),qs=o(s,"P",{});var rl=p(qs);mr=n(rl,"Finally, bring everything together, and call "),Xa=o(rl,"A",{href:!0});var Lc=p(Xa);ur=n(Lc,"train()"),Lc.forEach(e),dr=n(rl,":"),rl.forEach(e),$n=h(s),d(ma.$$.fragment,s),Dn=h(s),A=o(s,"P",{});var ns=p(A);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 `),se=o(ns,"A",{href:!0});var Sc=p(se);yr=n(Sc,"push_to_hub()"),Sc.forEach(e),xr=n(ns," method."),ns.forEach(e),Tn=h(s),d(ua.$$.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(da.$$.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),An=n(s,`

Object detection models are commonly evaluated with a set of `),ga=o(s,"A",{href:!0});var Gc=p(ga);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 he=p(ss);$r=n(he,"To use the "),wt=o(he,"CODE",{});var Bc=p(wt);Dr=n(Bc,"torchvision"),Bc.forEach(e),Tr=n(he,` 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(he,"CODE",{});var Kc=p(yt);Cr=n(Kc,'cppe5["test"]'),Kc.forEach(e),Ar=n(he,` need to be formatted. However, images
should stay as they are.`),he.forEach(e),On=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);Or=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(fa.$$.fragment,s),zn=h(s),as=o(s,"P",{});var me=p(as);zr=n(me,"Next, prepare an instance of a "),qt=o(me,"CODE",{});var Jc=p(qt);Fr=n(Jc,"CocoDetection"),Jc.forEach(e),Lr=n(me," class that can be used with "),Et=o(me,"CODE",{});var Vc=p(Et);Rr=n(Vc,"cocoevaluator"),Vc.forEach(e),Hr=n(me,"."),me.forEach(e),Fn=h(s),d(ja.$$.fragment,s),Ln=h(s),ae=o(s,"P",{});var Qc=p(ae);Mr=n(Qc,"Finally, load the metrics and run the evaluation."),Qc.forEach(e),Rn=h(s),d(ba.$$.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 "),ee=o(hl,"A",{href:!0});var Zc=p(ee);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(_a.$$.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.29.0/en/main_classes/pipelines#transformers.Pipeline). Instantiate a pipeline
for object detection with your model, and pass an image to it:

	`),d(va.$$.fragment,s),Un=h(s),te=o(s,"P",{});var eh=p(te);Br=n(eh,"You can also manually replicate the results of the pipeline if you\u2019d like:"),eh.forEach(e),Yn=h(s),d(wa.$$.fragment,s),Nn=h(s),ne=o(s,"P",{});var th=p(ne);Kr=n(th,"Let\u2019s plot the result:"),th.forEach(e),Gn=h(s),d(ya.$$.fragment,s),Bn=h(s),xa=o(s,"DIV",{class:!0});var nh=p(xa);le=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(Sa.src,Xr="https://i.imgur.com/TdaqPJO.png")||m(Sa,"src",Xr),m(Sa,"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(Ya,"href","/docs/transformers/v4.29.0/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(ea,"href","https://huggingface.co/docs/datasets/v2.12.0/en/package_reference/main_classes#datasets.Dataset.with_transform"),m(ea,"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(Wa,"href","/docs/transformers/v4.29.0/en/model_doc/auto#transformers.AutoModelForObjectDetection"),m(Ja,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.TrainingArguments"),m(Va,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer"),m(Qa,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer.train"),m(Za,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.TrainingArguments"),m(Xa,"href","/docs/transformers/v4.29.0/en/main_classes/trainer#transformers.Trainer.train"),m(se,"href","/docs/transformers/v4.29.0/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(ga,"href","https://cocodataset.org/#detection-eval"),m(ee,"href","/docs/transformers/v4.29.0/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(le.src,si="https://i.imgur.com/4QZnf9A.png")||m(le,"src",si),m(le,"alt","Object detection result on a new image"),m(xa,"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,O,r),a(O,x),a(x,y),a(x,W),a(W,Ea),a(x,ka),a(x,J),a(J,$a),a(x,Da),a(O,ul),a(O,de),a(de,dl),i(s,At,r),g(us,s,r),i(s,Pt,r),i(s,Ta,r),a(Ta,gl),i(s,Ot,r),g(Rs,s,r),i(s,It,r),i(s,V,r),a(V,fl),a(V,ge),a(ge,jl),a(V,bl),a(V,fe),a(fe,_l),a(V,vl),i(s,zt,r),i(s,Ca,r),a(Ca,wl),i(s,Ft,r),g(Hs,s,r),i(s,Lt,r),i(s,ps,r),a(ps,ds),a(ds,je),g(Ms,je,null),a(ps,yl),a(ps,be),a(be,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,Aa,r),a(Aa,$l),i(s,Mt,r),g(Us,s,r),i(s,St,r),i(s,Pa,r),a(Pa,Dl),i(s,Ut,r),i(s,Oa,r),a(Oa,Tl),i(s,Yt,r),g(Ys,s,r),i(s,Nt,r),i(s,Ia,r),a(Ia,Cl),i(s,Gt,r),i(s,T,r),a(T,za),a(za,_e),a(_e,Al),a(za,Pl),a(T,Ol),a(T,fs),a(fs,ve),a(ve,Il),a(fs,zl),a(fs,we),a(we,Fl),a(fs,Ll),a(T,Rl),a(T,Fa),a(Fa,ye),a(ye,Hl),a(Fa,Ml),a(T,Sl),a(T,La),a(La,xe),a(xe,Ul),a(La,Yl),a(T,Nl),a(T,Ns),a(Ns,qe),a(qe,Gl),a(Ns,Bl),a(Ns,N),a(N,Ra),a(Ra,Ee),a(Ee,Kl),a(Ra,Wl),a(N,Jl),a(N,Ha),a(Ha,ke),a(ke,Vl),a(Ha,Ql),a(N,Zl),a(N,js),a(js,$e),a($e,Xl),a(js,so),a(js,Gs),a(Gs,ao),a(js,eo),a(N,to),a(N,k),a(k,De),a(De,no),a(k,lo),a(k,Te),a(Te,oo),a(k,po),a(k,Ce),a(Ce,ro),a(k,io),a(k,Ae),a(Ae,co),a(k,ho),a(k,Pe),a(Pe,mo),a(k,uo),a(k,Oe),a(Oe,go),i(s,Bt,r),i(s,Q,r),a(Q,fo),a(Q,Ie),a(Ie,jo),a(Q,bo),a(Q,ze),a(ze,_o),a(Q,vo),i(s,Kt,r),i(s,Ma,r),a(Ma,wo),i(s,Wt,r),g(Bs,s,r),i(s,Jt,r),i(s,Ks,r),a(Ks,Sa),i(s,Vt,r),i(s,I,r),a(I,yo),a(I,Fe),a(Fe,xo),a(I,qo),a(I,Le),a(Le,Eo),a(I,ko),a(I,Re),a(Re,$o),a(I,Do),i(s,Qt,r),i(s,Ua,r),a(Ua,To),i(s,Zt,r),g(Ws,s,r),i(s,Xt,r),i(s,rs,r),a(rs,bs),a(bs,He),g(Js,He,null),a(rs,Co),a(rs,Me),a(Me,Ao),i(s,sn,r),i(s,C,r),a(C,Po),a(C,Ya),a(Ya,Oo),a(C,Io),a(C,Se),a(Se,zo),a(C,Fo),a(C,Ue),a(Ue,Lo),a(C,Ro),a(C,Ye),a(Ye,Ho),a(C,Mo),i(s,an,r),i(s,_s,r),a(_s,Ne),a(Ne,Ge),a(Ge,So),a(_s,Uo),a(_s,Be),a(Be,Ke),a(Ke,Yo),i(s,en,r),i(s,Na,r),a(Na,No),i(s,tn,r),i(s,Ga,r),a(Ga,Go),i(s,nn,r),g(Vs,s,r),i(s,ln,r),i(s,vs,r),a(vs,Bo),a(vs,We),a(We,Ko),a(vs,Wo),i(s,on,r),i(s,ws,r),a(ws,Je),a(Je,Jo),a(ws,Vo),a(ws,Ve),a(Ve,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,Qe),a(Qe,np),a(X,lp),a(X,Ze),a(Ze,op),a(X,pp),i(s,hn,r),g(sa,s,r),i(s,mn,r),i(s,Ba,r),a(Ba,rp),i(s,un,r),g(aa,s,r),i(s,dn,r),i(s,ys,r),a(ys,ip),a(ys,ea),a(ea,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(ta,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(na,s,r),i(s,_n,r),i(s,is,r),a(is,xs),a(xs,lt),g(la,lt,null),a(is,kp),a(is,ot),a(ot,$p),i(s,vn,r),i(s,Ka,r),a(Ka,Dp),i(s,wn,r),i(s,L,r),a(L,oa),a(oa,Tp),a(oa,Wa),a(Wa,Cp),a(oa,Ap),a(L,Pp),a(L,pa),a(pa,Op),a(pa,Ja),a(Ja,Ip),a(pa,zp),a(L,Fp),a(L,ra),a(ra,Lp),a(ra,Va),a(Va,Rp),a(ra,Hp),a(L,Mp),a(L,ia),a(ia,Sp),a(ia,Qa),a(Qa,Up),a(ia,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(ca,s,r),i(s,qn,r),i(s,w,r),a(w,Qp),a(w,Za),a(Za,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(ha,s,r),i(s,kn,r),i(s,qs,r),a(qs,mr),a(qs,Xa),a(Xa,ur),a(qs,dr),i(s,$n,r),g(ma,s,r),i(s,Dn,r),i(s,A,r),a(A,gr),a(A,ft),a(ft,fr),a(A,jr),a(A,jt),a(jt,br),a(A,_r),a(A,bt),a(bt,vr),a(A,wr),a(A,se),a(se,yr),a(A,xr),i(s,Tn,r),g(ua,s,r),i(s,Cn,r),i(s,cs,r),a(cs,Es),a(Es,_t),g(da,_t,null),a(cs,qr),a(cs,vt),a(vt,Er),i(s,An,r),i(s,ga,r),a(ga,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,Ar),i(s,On,r),i(s,ks,r),a(ks,Pr),a(ks,xt),a(xt,Or),a(ks,Ir),i(s,In,r),g(fa,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(ja,s,r),i(s,Ln,r),i(s,ae,r),a(ae,Mr),i(s,Rn,r),g(ba,s,r),i(s,Hn,r),i(s,$s,r),a($s,Sr),a($s,ee),a(ee,Ur),a($s,Yr),i(s,Mn,r),i(s,hs,r),a(hs,Ds),a(Ds,kt),g(_a,kt,null),a(hs,Nr),a(hs,$t),a($t,Gr),i(s,Sn,r),g(va,s,r),i(s,Un,r),i(s,te,r),a(te,Br),i(s,Yn,r),g(wa,s,r),i(s,Nn,r),i(s,ne,r),a(ne,Kr),i(s,Gn,r),g(ya,s,r),i(s,Bn,r),i(s,xa,r),a(xa,le),Kn=!0},p(s,[r]){const qa={};r&2&&(qa.$$scope={dirty:r,ctx:s}),us.$set(qa)},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(ta.$$.fragment,s),f(na.$$.fragment,s),f(la.$$.fragment,s),f(ca.$$.fragment,s),f(ha.$$.fragment,s),f(ma.$$.fragment,s),f(ua.$$.fragment,s),f(da.$$.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),f(ya.$$.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(ta.$$.fragment,s),j(na.$$.fragment,s),j(la.$$.fragment,s),j(ca.$$.fragment,s),j(ha.$$.fragment,s),j(ma.$$.fragment,s),j(ua.$$.fragment,s),j(da.$$.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),j(ya.$$.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(O),s&&e(At),b(us,s),s&&e(Pt),s&&e(Ta),s&&e(Ot),b(Rs,s),s&&e(It),s&&e(V),s&&e(zt),s&&e(Ca),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(Aa),s&&e(Mt),b(Us,s),s&&e(St),s&&e(Pa),s&&e(Ut),s&&e(Oa),s&&e(Yt),b(Ys,s),s&&e(Nt),s&&e(Ia),s&&e(Gt),s&&e(T),s&&e(Bt),s&&e(Q),s&&e(Kt),s&&e(Ma),s&&e(Wt),b(Bs,s),s&&e(Jt),s&&e(Ks),s&&e(Vt),s&&e(I),s&&e(Qt),s&&e(Ua),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(Na),s&&e(tn),s&&e(Ga),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(Ba),s&&e(un),b(aa,s),s&&e(dn),s&&e(ys),s&&e(gn),s&&e(z),s&&e(fn),b(ta,s),s&&e(jn),s&&e(F),s&&e(bn),b(na,s),s&&e(_n),s&&e(is),b(la),s&&e(vn),s&&e(Ka),s&&e(wn),s&&e(L),s&&e(yn),s&&e(R),s&&e(xn),b(ca,s),s&&e(qn),s&&e(w),s&&e(En),b(ha,s),s&&e(kn),s&&e(qs),s&&e($n),b(ma,s),s&&e(Dn),s&&e(A),s&&e(Tn),b(ua,s),s&&e(Cn),s&&e(cs),b(da),s&&e(An),s&&e(ga),s&&e(Pn),s&&e(ss),s&&e(On),s&&e(ks),s&&e(In),b(fa,s),s&&e(zn),s&&e(as),s&&e(Fn),b(ja,s),s&&e(Ln),s&&e(ae),s&&e(Rn),b(ba,s),s&&e(Hn),s&&e($s),s&&e(Mn),s&&e(hs),b(_a),s&&e(Sn),b(va,s),s&&e(Un),s&&e(te),s&&e(Yn),b(wa,s),s&&e(Nn),s&&e(ne),s&&e(Gn),b(ya,s),s&&e(Bn),s&&e(xa)}}}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};
