Buckets:

hf-doc-build/doc / transformers /main /ru /tasks /object_detection.html
mishig's picture
download
raw
98.6 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Обнаружение объектов&quot;,&quot;local&quot;:&quot;object-detection&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Загрузите набор данных mobile-ui-design&quot;,&quot;local&quot;:&quot;load-the-mobile-ui-design-dataset&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Предобработка данных&quot;,&quot;local&quot;:&quot;preprocess-the-data&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Аугментация данных&quot;,&quot;local&quot;:&quot;data-augmentation&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Подготовка функции для вычисления mAP&quot;,&quot;local&quot;:&quot;preparing-function-to-compute-map&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Обучение модели обнаружения&quot;,&quot;local&quot;:&quot;training-the-detection-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Оценка&quot;,&quot;local&quot;:&quot;evaluate&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Вывод&quot;,&quot;local&quot;:&quot;inference&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/>
<link href="/docs/transformers/main/en/_app/immutable/entry/start.DYIO-UII.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DSYYoqAA.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/BovLmb3z.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/entry/app.D2_KizbC.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/WyYpyc-L.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DYBfcveH.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DOLBYqcr.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DsnmJJEf.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/0.ByO_lNbj.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/ZtBhN-Ei.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/756.Cv5zViYe.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/D-dvW--N.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/5hn6CH6J.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/Bz_scJS3.js" rel="modulepreload">
<!--dp8gch--><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Object detection&quot;,&quot;local&quot;:&quot;object-detection&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Load the mobile-ui-design dataset&quot;,&quot;local&quot;:&quot;load-the-mobile-ui-design-dataset&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Preprocess the data&quot;,&quot;local&quot;:&quot;preprocess-the-data&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Data augmentation&quot;,&quot;local&quot;:&quot;data-augmentation&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Preparing function to compute mAP&quot;,&quot;local&quot;:&quot;preparing-function-to-compute-map&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Training the detection model&quot;,&quot;local&quot;:&quot;training-the-detection-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Evaluate&quot;,&quot;local&quot;:&quot;evaluate&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Inference&quot;,&quot;local&quot;:&quot;inference&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/><!---->
<link href="/docs/transformers/main/en/_app/immutable/assets/0.tn0RQdqM.css" rel="modulepreload"> <!--[--><!--[0--><!--[--><!--[0--><!--[--><p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;"><div dir="ltr" class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 h-7 max-sm:h-7 px-2 max-sm:px-1.5 text-sm font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0 hover:text-gray-800 dark:hover:text-gray-200"><svg class="sm:size-3.5 size-3" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----></span> <span dir="auto">Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-7 max-sm:h-7 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible sm:size-3.5 size-3 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg><!----></button></div> <!--[-1--><!--]--></div><!----> <div class="flex space-x-1 " style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;" dir="ltr"><!----> <!--[1--><div class="relative colab-dropdown "><button class=" " type="button"><!--[0--><!--[-1--><img alt="Open In Colab" class="!m-0" src="https://colab.research.google.com/assets/colab-badge.svg"/><!--]--><!----><!--]--></button> <!--[-1--><!--]--></div><!--]--> <!--[1--><div class="relative colab-dropdown "><button class=" " type="button"><!--[0--><!--[-1--><img alt="Open In Studio Lab" class="!m-0" src="https://studiolab.sagemaker.aws/studiolab.svg"/><!--]--><!----><!--]--></button> <!--[-1--><!--]--></div><!--]--></div><!----> <!--[0--><h1 class="relative group"><a id="object-detection" 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" href="#object-detection"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Обнаружение объектов<!----></span></h1><!--]--><!----> <p>Обнаружение объектов — это задача компьютерного зрения, состоящая в определении экземпляров объектов (например, людей, зданий или автомобилей) на изображении. Модели обнаружения объектов принимают на вход изображение и на выходе предоставляют координаты ограничивающих прямоугольников и соответствующие им метки обнаруженных объектов. На одном изображении может присутствовать несколько объектов, каждый со своим ограничивающим прямоугольником и меткой (например, автомобиль и здание), при этом каждый объект может находиться в разных частях изображения (например, на изображении может быть несколько автомобилей).
Эта задача широко применяется в автономном вождении для обнаружения таких объектов, как пешеходы, дорожные знаки и светофоры.
Среди других приложений — подсчёт объектов на изображениях, поиск по изображениям и многое другое.</p> <p>В этом руководстве вы узнаете, как:</p> <ol><li>Настройте <a href="https://huggingface.co/Roboflow/rf-detr-medium" rel="nofollow">RF-DETR</a> на датасете <a href="https://huggingface.co/datasets/merve/mobile-ui-design" rel="nofollow">mobile-ui-design</a> для обнаружения элементов пользовательского интерфейса на скриншотах мобильных приложений.</li> <li>Используйте вашу дообученную модель для инференса.</li></ol> <blockquote class="tip"><p>Чтобы увидеть все архитектуры и контрольные точки, совместимые с этой задачей, рекомендуем обратиться к <a href="https://huggingface.co/tasks/object-detection" rel="nofollow">странице задачи</a></p><!----></blockquote><!----> <p>Прежде чем начать, убедитесь, что у вас установлены все необходимые библиотеки:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-bash "><!---->pip install -q datasets transformers accelerate timm trackio torchmetrics pycocotools<!----></pre></div><!----> <p>Вы будете использовать 🤗 Datasets для загрузки набора данных из Hugging Face Hub и 🤗 Transformers для обучения модели.</p> <p>Мы рекомендуем делиться вашей моделью с сообществом. Войдите в свой аккаунт Hugging Face, чтобы загрузить её на Hub.
При запросе введите токен для входа:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><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()<!----></pre></div><!----> <p>Определите глобальные константы, а именно имя модели и размер изображения. В этом учебном материале используется RF-DETR, но вы можете выбрать любую модель обнаружения объектов в Transformers.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>MODEL_NAME = <span class="hljs-string">&quot;Roboflow/rf-detr-medium&quot;</span><!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="load-the-mobile-ui-design-dataset" 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" href="#load-the-mobile-ui-design-dataset"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Загрузите набор данных mobile-ui-design<!----></span></h2><!--]--><!----> <p>Набор данных <a href="https://huggingface.co/datasets/merve/mobile-ui-design" rel="nofollow">mobile-ui-design</a> содержит скриншоты мобильных приложений с аннотациями для обнаружения элементов пользовательского интерфейса, таких как текст, изображения, прямоугольники и группы.</p> <p>Начните с загрузки набора данных и извлечения меток категорий. В наборе данных уже есть разбиения.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><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>ds = load_dataset(<span class="hljs-string">&quot;merve/mobile-ui-design&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>CATEGORIES = <span class="hljs-built_in">sorted</span>(<span class="hljs-built_in">set</span>(
<span class="hljs-meta">... </span> cat <span class="hljs-keyword">for</span> split <span class="hljs-keyword">in</span> ds.values() <span class="hljs-keyword">for</span> example <span class="hljs-keyword">in</span> split <span class="hljs-keyword">for</span> cat <span class="hljs-keyword">in</span> example[<span class="hljs-string">&quot;objects&quot;</span>][<span class="hljs-string">&quot;category&quot;</span>]
<span class="hljs-meta">... </span>))
<span class="hljs-meta">&gt;&gt;&gt; </span>label2id = {label: i <span class="hljs-keyword">for</span> i, label <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(CATEGORIES)}
<span class="hljs-meta">&gt;&gt;&gt; </span>id2label = {i: label <span class="hljs-keyword">for</span> label, i <span class="hljs-keyword">in</span> label2id.items()}
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Categories (<span class="hljs-subst">{<span class="hljs-built_in">len</span>(CATEGORIES)}</span>): <span class="hljs-subst">{CATEGORIES}</span>&quot;</span>)
Categories (<span class="hljs-number">4</span>): [<span class="hljs-string">&#x27;group&#x27;</span>, <span class="hljs-string">&#x27;image&#x27;</span>, <span class="hljs-string">&#x27;rectangle&#x27;</span>, <span class="hljs-string">&#x27;text&#x27;</span>]<!----></pre></div><!----> <p>Набор данных использует строковые имена категорий и ограничивающие рамки в формате COCO <code>(x, y, w, h)</code>. Перед обучением преобразуйте категории в целочисленные идентификаторы, вычислите площади и отфильтруйте вырожденные ограничивающие рамки:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">prepare_example</span>(<span class="hljs-params">example, idx</span>):
<span class="hljs-meta">... </span> objects = example[<span class="hljs-string">&quot;objects&quot;</span>]
<span class="hljs-meta">... </span> in_bboxes = objects[<span class="hljs-string">&quot;bbox&quot;</span>]
<span class="hljs-meta">... </span> categories = objects[<span class="hljs-string">&quot;category&quot;</span>]
<span class="hljs-meta">... </span> img_w, img_h = example[<span class="hljs-string">&quot;width&quot;</span>], example[<span class="hljs-string">&quot;height&quot;</span>]
<span class="hljs-meta">... </span> bboxes, cats, areas, ids = [], [], [], []
<span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> i, (bbox, cat) <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(<span class="hljs-built_in">zip</span>(in_bboxes, categories)):
<span class="hljs-meta">... </span> x, y, w, h = bbox
<span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> w &lt;= <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> h &lt;= <span class="hljs-number">0</span>:
<span class="hljs-meta">... </span> <span class="hljs-keyword">continue</span>
<span class="hljs-meta">... </span> x = <span class="hljs-built_in">max</span>(<span class="hljs-number">0.0</span>, <span class="hljs-built_in">min</span>(x, img_w))
<span class="hljs-meta">... </span> y = <span class="hljs-built_in">max</span>(<span class="hljs-number">0.0</span>, <span class="hljs-built_in">min</span>(y, img_h))
<span class="hljs-meta">... </span> w = <span class="hljs-built_in">min</span>(w, img_w - x)
<span class="hljs-meta">... </span> h = <span class="hljs-built_in">min</span>(h, img_h - y)
<span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> w &lt;= <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> h &lt;= <span class="hljs-number">0</span>:
<span class="hljs-meta">... </span> <span class="hljs-keyword">continue</span>
<span class="hljs-meta">... </span> bboxes.append([x, y, w, h])
<span class="hljs-meta">... </span> cats.append(label2id[cat])
<span class="hljs-meta">... </span> areas.append(w * h)
<span class="hljs-meta">... </span> ids.append(i)
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> {
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;image_id&quot;</span>: idx, <span class="hljs-string">&quot;image&quot;</span>: example[<span class="hljs-string">&quot;image&quot;</span>],
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;width&quot;</span>: example[<span class="hljs-string">&quot;width&quot;</span>], <span class="hljs-string">&quot;height&quot;</span>: example[<span class="hljs-string">&quot;height&quot;</span>],
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;objects&quot;</span>: {<span class="hljs-string">&quot;id&quot;</span>: ids, <span class="hljs-string">&quot;bbox&quot;</span>: bboxes, <span class="hljs-string">&quot;category&quot;</span>: cats, <span class="hljs-string">&quot;area&quot;</span>: areas},
<span class="hljs-meta">... </span> }
<span class="hljs-meta">&gt;&gt;&gt; </span>ds_prepared = ds[<span class="hljs-string">&quot;train&quot;</span>].<span class="hljs-built_in">map</span>(prepare_example, with_indices=<span class="hljs-literal">True</span>, remove_columns=ds[<span class="hljs-string">&quot;train&quot;</span>].column_names)
<span class="hljs-meta">&gt;&gt;&gt; </span>ds_prepared = ds_prepared.<span class="hljs-built_in">filter</span>(<span class="hljs-keyword">lambda</span> x: <span class="hljs-built_in">len</span>(x[<span class="hljs-string">&quot;objects&quot;</span>][<span class="hljs-string">&quot;bbox&quot;</span>]) &gt; <span class="hljs-number">0</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>split = ds_prepared.train_test_split(test_size=<span class="hljs-number">0.15</span>, seed=<span class="hljs-number">1337</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>train_ds = split[<span class="hljs-string">&quot;train&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>val_ds = split[<span class="hljs-string">&quot;test&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Train: <span class="hljs-subst">{<span class="hljs-built_in">len</span>(train_ds)}</span>, Validation: <span class="hljs-subst">{<span class="hljs-built_in">len</span>(val_ds)}</span>&quot;</span>)
Train: <span class="hljs-number">6669</span>, Validation: <span class="hljs-number">1177</span><!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="preprocess-the-data" 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" href="#preprocess-the-data"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Предобработка данных<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/ru/model_doc/auto#transformers.AutoImageProcessor">AutoImageProcessor</a> отвечает за обработку изображений с целью создания <code>pixel_values</code>, <code>pixel_mask</code> и <code>labels</code>, на которых обучается модель. Процессор изображений выполняет изменение размера, добавление отступов и нормализацию. Кроме того, вы можете по желанию добавить случайные преобразования данных (см. <a href="#data-augmentation">ниже</a>) для улучшения обобщающей способности.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><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">from</span> functools <span class="hljs-keyword">import</span> partial
<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>image_processor = AutoImageProcessor.from_pretrained(MODEL_NAME)<!----></pre></div><!----> <p>Объект <code>image_processor</code> ожидает аннотации в формате COCO: <code>{'image_id': int, 'annotations': list[Dict]}</code>. Сформируйте аннотации для каждого примера, а остальное обработчик возьмет на себя:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">format_image_annotations_as_coco</span>(<span class="hljs-params">image_id, categories, areas, bboxes</span>):
<span class="hljs-meta">... </span> annotations = []
<span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> category, area, bbox <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(categories, areas, bboxes):
<span class="hljs-meta">... </span> annotations.append({
<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,
<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,
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;bbox&quot;</span>: <span class="hljs-built_in">list</span>(bbox),
<span class="hljs-meta">... </span> })
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> {<span class="hljs-string">&quot;image_id&quot;</span>: image_id, <span class="hljs-string">&quot;annotations&quot;</span>: annotations}
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">transform_batch</span>(<span class="hljs-params">examples, image_processor</span>):
<span class="hljs-meta">... </span> images = []
<span class="hljs-meta">... </span> annotations = []
<span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> image_id, image, objects <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(examples[<span class="hljs-string">&quot;image_id&quot;</span>], examples[<span class="hljs-string">&quot;image&quot;</span>], examples[<span class="hljs-string">&quot;objects&quot;</span>]):
<span class="hljs-meta">... </span> images.append(np.array(image.convert(<span class="hljs-string">&quot;RGB&quot;</span>)))
<span class="hljs-meta">... </span> formatted = format_image_annotations_as_coco(
<span class="hljs-meta">... </span> image_id, objects[<span class="hljs-string">&quot;category&quot;</span>], objects[<span class="hljs-string">&quot;area&quot;</span>], objects[<span class="hljs-string">&quot;bbox&quot;</span>]
<span class="hljs-meta">... </span> )
<span class="hljs-meta">... </span> annotations.append(formatted)
<span class="hljs-meta">... </span> result = image_processor(images=images, annotations=annotations, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
<span class="hljs-meta">... </span> result.pop(<span class="hljs-string">&quot;pixel_mask&quot;</span>, <span class="hljs-literal">None</span>)
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> result
<span class="hljs-meta">&gt;&gt;&gt; </span>transform_fn = partial(transform_batch, image_processor=image_processor)
<span class="hljs-meta">&gt;&gt;&gt; </span>train_ds = train_ds.with_transform(transform_fn)
<span class="hljs-meta">&gt;&gt;&gt; </span>val_ds = val_ds.with_transform(transform_fn)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="data-augmentation" 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" href="#data-augmentation"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Аугментация данных<!----></span></h3><!--]--><!----> <p>Преобразование выше выполняет только изменение размера и нормализацию изображений. Случайные аугментации, применяемые к разбиению <strong>training</strong>, как правило, улучшают обобщение, тогда как разбиение валидации должно оставаться без аугментаций, чтобы оценка оставалась детерминированной. Распространённым выбором является <a href="https://albumentations.ai/" rel="nofollow">Albumentations</a>, который аугментирует изображение и его ограничивающие рамки совместно. Определите конвейер с <code>bbox_params</code>, чтобы рамки трансформировались согласованно с изображением, а затем пересчитайте площади по аугментированным рамкам:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> albumentations <span class="hljs-keyword">as</span> A
<span class="hljs-meta">&gt;&gt;&gt; </span>train_augment = A.Compose(
<span class="hljs-meta">... </span> [
<span class="hljs-meta">... </span> A.Perspective(p=<span class="hljs-number">0.1</span>),
<span class="hljs-meta">... </span> A.HorizontalFlip(p=<span class="hljs-number">0.5</span>),
<span class="hljs-meta">... </span> A.RandomBrightnessContrast(p=<span class="hljs-number">0.5</span>),
<span class="hljs-meta">... </span> A.HueSaturationValue(p=<span class="hljs-number">0.1</span>),
<span class="hljs-meta">... </span> ],
<span class="hljs-meta">... </span> bbox_params=A.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>], clip=<span class="hljs-literal">True</span>, min_area=<span class="hljs-number">25</span>),
<span class="hljs-meta">... </span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">augment_and_transform_batch</span>(<span class="hljs-params">examples, image_processor, transform</span>):
<span class="hljs-meta">... </span> images = []
<span class="hljs-meta">... </span> annotations = []
<span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> image_id, image, objects <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(examples[<span class="hljs-string">&quot;image_id&quot;</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-meta">... </span> output = 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> images.append(output[<span class="hljs-string">&quot;image&quot;</span>])
<span class="hljs-meta">... </span> areas = [w * h <span class="hljs-keyword">for</span> (_, _, w, h) <span class="hljs-keyword">in</span> output[<span class="hljs-string">&quot;bboxes&quot;</span>]]
<span class="hljs-meta">... </span> formatted = format_image_annotations_as_coco(
<span class="hljs-meta">... </span> image_id, output[<span class="hljs-string">&quot;category&quot;</span>], areas, output[<span class="hljs-string">&quot;bboxes&quot;</span>]
<span class="hljs-meta">... </span> )
<span class="hljs-meta">... </span> annotations.append(formatted)
<span class="hljs-meta">... </span> result = image_processor(images=images, annotations=annotations, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)
<span class="hljs-meta">... </span> result.pop(<span class="hljs-string">&quot;pixel_mask&quot;</span>, <span class="hljs-literal">None</span>)
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> result<!----></pre></div><!----> <p>Примените трансформацию аугментации только к обучающей выборке, а для валидации оставьте обычную <code>transform_fn</code>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>train_augment_fn = partial(augment_and_transform_batch, image_processor=image_processor, transform=train_augment)
<span class="hljs-meta">&gt;&gt;&gt; </span>train_ds = train_ds.with_transform(train_augment_fn)
<span class="hljs-meta">&gt;&gt;&gt; </span>val_ds = val_ds.with_transform(transform_fn)<!----></pre></div><!----> <p>Создайте собственную <code>collate_fn</code> для пакетирования изображений:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch
<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> data = {}
<span class="hljs-meta">... </span> data[<span class="hljs-string">&quot;pixel_values&quot;</span>] = torch.stack([x[<span class="hljs-string">&quot;pixel_values&quot;</span>] <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> batch])
<span class="hljs-meta">... </span> data[<span class="hljs-string">&quot;labels&quot;</span>] = [x[<span class="hljs-string">&quot;labels&quot;</span>] <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> batch]
<span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> <span class="hljs-string">&quot;pixel_mask&quot;</span> <span class="hljs-keyword">in</span> batch[<span class="hljs-number">0</span>]:
<span class="hljs-meta">... </span> data[<span class="hljs-string">&quot;pixel_mask&quot;</span>] = torch.stack([x[<span class="hljs-string">&quot;pixel_mask&quot;</span>] <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> batch])
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> data
<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="preparing-function-to-compute-map" 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" href="#preparing-function-to-compute-map"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Подготовка функции для вычисления mAP<!----></span></h2><!--]--><!----> <p>Модели обнаружения объектов обычно оцениваются с помощью набора <a href="https://cocodataset.org/#detection-eval">метрик в стиле COCO</a>. Мы будем использовать <code>torchmetrics</code> для вычисления метрик <code>mAP</code> (средняя средняя точность) и <code>mAR</code> (средняя средняя полнота) и обернем их в функцию <code>compute_metrics</code>, чтобы использовать в <a href="/docs/transformers/main/ru/main_classes/trainer#transformers.Trainer">Trainer</a> для оценки.</p> <p>Промежуточный формат рамок, используемый для обучения, — это <code>YOLO</code> (нормализованный), однако для корректной обработки площадей рамок метрики будут вычисляться в формате <code>Pascal VOC</code> (абсолютные значения). Определим функцию, преобразующую рамки в формат <code>Pascal VOC</code>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers.image_transforms <span class="hljs-keyword">import</span> center_to_corners_format
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">convert_bbox_yolo_to_pascal</span>(<span class="hljs-params">boxes, image_size</span>):
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;&quot;&quot;
<span class="hljs-meta">... </span> Convert bounding boxes from YOLO format (x_center, y_center, width, height) in range [0, 1]
<span class="hljs-meta">... </span> to Pascal VOC format (x_min, y_min, x_max, y_max) in absolute coordinates.
<span class="hljs-meta">... </span> Args:
<span class="hljs-meta">... </span> boxes (torch.Tensor): Bounding boxes in YOLO format
<span class="hljs-meta">... </span> image_size (tuple[int, int]): Image size in format (height, width)
<span class="hljs-meta">... </span> Returns:
<span class="hljs-meta">... </span> torch.Tensor: Bounding boxes in Pascal VOC format (x_min, y_min, x_max, y_max)
<span class="hljs-meta">... </span> &quot;&quot;&quot;</span>
<span class="hljs-meta">... </span> <span class="hljs-comment"># convert center to corners format</span>
<span class="hljs-meta">... </span> boxes = center_to_corners_format(boxes)
<span class="hljs-meta">... </span> <span class="hljs-comment"># convert to absolute coordinates</span>
<span class="hljs-meta">... </span> height, width = image_size
<span class="hljs-meta">... </span> boxes = boxes * torch.tensor([[width, height, width, height]])
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> boxes<!----></pre></div><!----> <p>Затем в функции <code>compute_metrics</code> мы собираем предсказанные <code>predicted</code> и целевые <code>target</code> ограничивающие рамки, оценки и метки из результатов цикла оценки и передаём их в функцию подсчёта метрик.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><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">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> torchmetrics.detection.mean_ap <span class="hljs-keyword">import</span> MeanAveragePrecision
<span class="hljs-meta">&gt;&gt;&gt; </span>@dataclass
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">class</span> <span class="hljs-title class_">ModelOutput</span>:
<span class="hljs-meta">... </span> logits: torch.Tensor
<span class="hljs-meta">... </span> pred_boxes: torch.Tensor
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">_get_orig_size</span>(<span class="hljs-params">image_target</span>):
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;&quot;&quot;Robust orig_size extraction - Trainer serialization can truncate to 1 element.&quot;&quot;&quot;</span>
<span class="hljs-meta">... </span> orig = np.atleast_1d(np.asarray(image_target[<span class="hljs-string">&quot;orig_size&quot;</span>])).flatten()
<span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(orig) &gt;= <span class="hljs-number">2</span>:
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> (<span class="hljs-built_in">int</span>(orig[<span class="hljs-number">0</span>]), <span class="hljs-built_in">int</span>(orig[<span class="hljs-number">1</span>]))
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> (<span class="hljs-built_in">int</span>(orig[<span class="hljs-number">0</span>]), <span class="hljs-built_in">int</span>(orig[<span class="hljs-number">0</span>]))
<span class="hljs-meta">&gt;&gt;&gt; </span>@torch.no_grad()
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">compute_metrics</span>(<span class="hljs-params">evaluation_results, image_processor, threshold=<span class="hljs-number">0.0</span>, id2label=<span class="hljs-literal">None</span></span>):
<span class="hljs-meta">... </span> predictions, targets = evaluation_results.predictions, evaluation_results.label_ids
<span class="hljs-meta">... </span> image_sizes = []
<span class="hljs-meta">... </span> post_processed_targets = []
<span class="hljs-meta">... </span> post_processed_predictions = []
...
<span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> batch <span class="hljs-keyword">in</span> targets:
<span class="hljs-meta">... </span> batch_sizes = []
<span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> image_target <span class="hljs-keyword">in</span> batch:
<span class="hljs-meta">... </span> h, w = _get_orig_size(image_target)
<span class="hljs-meta">... </span> batch_sizes.append([h, w])
<span class="hljs-meta">... </span> boxes = torch.tensor(image_target[<span class="hljs-string">&quot;boxes&quot;</span>])
<span class="hljs-meta">... </span> boxes = convert_bbox_yolo_to_pascal(boxes, (h, w))
<span class="hljs-meta">... </span> labels = torch.tensor(image_target[<span class="hljs-string">&quot;class_labels&quot;</span>])
<span class="hljs-meta">... </span> post_processed_targets.append({<span class="hljs-string">&quot;boxes&quot;</span>: boxes, <span class="hljs-string">&quot;labels&quot;</span>: labels})
<span class="hljs-meta">... </span> image_sizes.append(torch.tensor(batch_sizes))
...
<span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> batch, target_sizes <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(predictions, image_sizes):
<span class="hljs-meta">... </span> batch_logits, batch_boxes = batch[<span class="hljs-number">1</span>], batch[<span class="hljs-number">2</span>]
<span class="hljs-meta">... </span> output = ModelOutput(logits=torch.tensor(batch_logits), pred_boxes=torch.tensor(batch_boxes))
<span class="hljs-meta">... </span> post_processed_output = image_processor.post_process_object_detection(
<span class="hljs-meta">... </span> output, threshold=threshold, target_sizes=target_sizes
<span class="hljs-meta">... </span> )
<span class="hljs-meta">... </span> post_processed_predictions.extend(post_processed_output)
...
<span class="hljs-meta">... </span> metric = MeanAveragePrecision(box_format=<span class="hljs-string">&quot;xyxy&quot;</span>, class_metrics=<span class="hljs-literal">True</span>)
<span class="hljs-meta">... </span> metric.update(post_processed_predictions, post_processed_targets)
<span class="hljs-meta">... </span> metrics = metric.compute()
...
<span class="hljs-meta">... </span> classes = metrics.pop(<span class="hljs-string">&quot;classes&quot;</span>)
<span class="hljs-meta">... </span> map_per_class = metrics.pop(<span class="hljs-string">&quot;map_per_class&quot;</span>)
<span class="hljs-meta">... </span> mar_100_per_class = metrics.pop(<span class="hljs-string">&quot;mar_100_per_class&quot;</span>)
<span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> class_id, class_map, class_mar <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(classes, map_per_class, mar_100_per_class):
<span class="hljs-meta">... </span> class_name = id2label[class_id.item()] <span class="hljs-keyword">if</span> id2label <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">else</span> class_id.item()
<span class="hljs-meta">... </span> metrics[<span class="hljs-string">f&quot;map_<span class="hljs-subst">{class_name}</span>&quot;</span>] = class_map
<span class="hljs-meta">... </span> metrics[<span class="hljs-string">f&quot;mar_100_<span class="hljs-subst">{class_name}</span>&quot;</span>] = class_mar
...
<span class="hljs-meta">... </span> metrics = {k: <span class="hljs-built_in">round</span>(v.item(), <span class="hljs-number">4</span>) <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> metrics.items()}
<span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> metrics
<span class="hljs-meta">&gt;&gt;&gt; </span>eval_compute_metrics_fn = partial(
<span class="hljs-meta">... </span> compute_metrics, image_processor=image_processor, id2label=id2label, threshold=<span class="hljs-number">0.0</span>
<span class="hljs-meta">... </span>)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="training-the-detection-model" 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" href="#training-the-detection-model"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Обучение модели обнаружения<!----></span></h2><!--]--><!----> <p>В предыдущих разделах вы выполнили основную работу, поэтому теперь вы готовы обучать свою модель!
Изображения в этом датасете по-прежнему достаточно большие, даже после изменения размера. Это означает, что дообучение этой модели потребует как минимум одного GPU.</p> <p>Обучение включает следующие шаги:</p> <ol><li>Загрузите модель с помощью <a href="/docs/transformers/main/ru/model_doc/auto#transformers.AutoModelForObjectDetection">AutoModelForObjectDetection</a>, используя тот же чекпоинт, что и при предобработке.</li> <li>Определите гиперпараметры обучения в <a href="/docs/transformers/main/ru/main_classes/trainer#transformers.TrainingArguments">TrainingArguments</a>.</li> <li>Передайте аргументы обучения в <a href="/docs/transformers/main/ru/main_classes/trainer#transformers.Trainer">Trainer</a> вместе с моделью, набором данных, процессором изображений и коллаборатором данных.</li> <li>Вызовите <a href="/docs/transformers/main/ru/main_classes/trainer#transformers.Trainer.train">train()</a>, чтобы дообучить модель.</li></ol> <p>При загрузке модели из того же контрольного пункта, который вы использовали для предобработки, не забудьте передать карты <code>label2id</code> и <code>id2label</code>, созданные ранее из метаданных набора данных. Кроме того, мы указываем <code>ignore_mismatched_sizes=True</code>, чтобы заменить существующую голову классификации новой.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><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> MODEL_NAME,
<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>)<!----></pre></div><!----> <p>В <a href="/docs/transformers/main/ru/main_classes/trainer#transformers.TrainingArguments">TrainingArguments</a> используйте <code>output_dir</code>, чтобы указать, куда сохранять модель, а затем настройте гиперпараметры по своему усмотрению. При <code>num_train_epochs=5</code> обучение займёт около 35 минут на GPU A100; увеличьте количество эпох, чтобы получить лучшие результаты.</p> <p>Важные примечания:</p> <ul><li>Не удаляйте неиспользуемые столбцы, так как это приведёт к удалению столбца с изображениями. Без столбца с изображениями невозможно создать <code>pixel_values</code>. По этой причине установите для <code>remove_unused_columns</code> значение <code>False</code>.</li> <li>Установите <code>eval_do_concat_batches=False</code>, чтобы получить корректные результаты оценки. У изображений разное количество целевых рамок; если батчи будут склеены, невозможно будет определить, какие рамки относятся к конкретному изображению.</li></ul> <p>Если вы хотите поделиться своей моделью, отправив её на Hub, установите <code>push_to_hub</code> в значение <code>True</code> (для загрузки модели необходимо войти в аккаунт Hugging Face).</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><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;rf_detr_finetuned_mobile_ui&quot;</span>,
<span class="hljs-meta">... </span> num_train_epochs=<span class="hljs-number">5</span>,
<span class="hljs-meta">... </span> bf16=<span class="hljs-literal">True</span>,
<span class="hljs-meta">... </span> per_device_train_batch_size=<span class="hljs-number">8</span>,
<span class="hljs-meta">... </span> dataloader_num_workers=<span class="hljs-number">4</span>,
<span class="hljs-meta">... </span> learning_rate=<span class="hljs-number">5e-5</span>,
<span class="hljs-meta">... </span> lr_scheduler_type=<span class="hljs-string">&quot;cosine&quot;</span>,
<span class="hljs-meta">... </span> weight_decay=<span class="hljs-number">1e-4</span>,
<span class="hljs-meta">... </span> max_grad_norm=<span class="hljs-number">0.01</span>,
<span class="hljs-meta">... </span> metric_for_best_model=<span class="hljs-string">&quot;eval_map&quot;</span>,
<span class="hljs-meta">... </span> greater_is_better=<span class="hljs-literal">True</span>,
<span class="hljs-meta">... </span> load_best_model_at_end=<span class="hljs-literal">True</span>,
<span class="hljs-meta">... </span> eval_strategy=<span class="hljs-string">&quot;epoch&quot;</span>,
<span class="hljs-meta">... </span> save_strategy=<span class="hljs-string">&quot;epoch&quot;</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> report_to=<span class="hljs-string">&quot;trackio&quot;</span>,
<span class="hljs-meta">... </span> run_name=<span class="hljs-string">&quot;mobile-ui-detection&quot;</span>,
<span class="hljs-meta">... </span> eval_do_concat_batches=<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>)<!----></pre></div><!----> <p>Наконец, соберите всё вместе и вызовите <a href="/docs/transformers/main/ru/main_classes/trainer#transformers.Trainer.train">train()</a>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><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> train_dataset=train_ds,
<span class="hljs-meta">... </span> eval_dataset=val_ds,
<span class="hljs-meta">... </span> processing_class=image_processor,
<span class="hljs-meta">... </span> data_collator=collate_fn,
<span class="hljs-meta">... </span> compute_metrics=eval_compute_metrics_fn,
<span class="hljs-meta">... </span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>trainer.train()<!----></pre></div><!----> <div><progress value="2085" max="2085" style="width:300px; height:20px; vertical-align: middle;"></progress> [2085/2085 38:39, Эпоха 5/5]</div> <table border="1" class="dataframe"><thead><tr style="text-align: left;"><th>Эпоха</th><th>Потери обучения</th><th>Потери валидации</th><th>Карта</th><th>Map 50</th><th>Карта 75</th><th>Map Small</th><th>Карта Medium</th><th>Map Large</th><th>1 марта</th><th>10 марта</th><th>100 марта</th><th>Mar Small</th><th>Mar Средний</th><th>Mar Large</th><th>Группа Map</th><th>Mar 100 Group</th><th>Карта изображения</th><th>Mar 100 Изображение</th><th>Карта прямоугольника</th><th>Mar 100 Прямоугольник</th><th>Карта текста</th><th>Mar 100 Text</th></tr></thead><tbody><tr><td>1</td><td>Нет журнала</td><td>9.9234</td><td>0.1303</td><td>0.2236</td><td>0.1478</td><td>0.0909</td><td>0.2030</td><td>0.2524</td><td>0.0421</td><td>0.2520</td><td>0.4683</td><td>0.3113</td><td>0.5607</td><td>0.6782</td><td>0.1244</td><td>0.5122</td><td>0.0958</td><td>0.5035</td><td>0.1285</td><td>0.4328</td><td>0.1725</td><td>0.4413</td></tr><tr><td>2</td><td>Нет журнала</td><td>9.8472</td><td>0.1893</td><td>0.3017</td><td>0.2124</td><td>0.1347</td><td>0.2789</td><td>0.3038</td><td>0.0549</td><td>0.2961</td><td>0.5140</td><td>0.3433</td><td>0.5941</td><td>0.7406</td><td>0.1305</td><td>0.5423</td><td>0.1979</td><td>0.5578</td><td>0.1964</td><td>0.4648</td><td>0.2324</td><td>0.4437</td></tr><tr><td>3</td><td>Нет журнала</td><td>9.6401</td><td>0.2275</td><td>0.3547</td><td>0.2657</td><td>0.1698</td><td>0.3336</td><td>0.3892</td><td>0.0611</td><td>0.3204</td><td>0.5270</td><td>0.3625</td><td>0.6143</td><td>0.7496</td><td>0.1602</td><td>0.5684</td><td>0.2617</td><td>0.5763</td><td>0.2249</td><td>0.4684</td><td>0.2631</td><td>0.4692</td></tr><tr><td>4</td><td>Нет журнала</td><td>9.5770</td><td>0.2733</td><td>0.4068</td><td>0.3133</td><td>0.2100</td><td>0.3867</td><td>0.4343</td><td>0.0668</td><td>0.3456</td><td>0.5593</td><td>0.3875</td><td>0.6393</td><td>0.7725</td><td>0.2013</td><td>0.5941</td><td>0.3158</td><td>0.6065</td><td>0.2733</td><td>0.4998</td><td>0.3028</td><td>0.4756</td></tr><tr><td>5</td><td>10.3700</td><td>11.0500</td><td>0.2827</td><td>0.4193</td><td>0.2913</td><td>0.2021</td><td>0.2814</td><td>0.3763</td><td>0.0609</td><td>0.3403</td><td>0.5668</td><td>0.4138</td><td>0.5669</td><td>0.7317</td><td>0.2092</td><td>0.5979</td><td>0.3334</td><td>0.6295</td><td>0.2793</td><td>0.5245</td><td>0.3089</td><td>0.5151</td></tr></tbody></table><p></p><p>Если в <code>training_args</code> параметр <code>push_to_hub</code> установлен в <code>True</code>, контрольные точки обучения будут загружены на Hugging Face Hub. По завершении обучения также загрузите итоговую модель на Hub, вызвав метод <a href="/docs/transformers/main/ru/main_classes/trainer#transformers.Trainer.push_to_hub">push_to_hub()</a>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>trainer.push_to_hub()<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="evaluate" 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" href="#evaluate"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Оценка<!----></span></h2><!--]--><!----> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> pprint <span class="hljs-keyword">import</span> pprint
<span class="hljs-meta">&gt;&gt;&gt; </span>metrics = trainer.evaluate(eval_dataset=val_ds, metric_key_prefix=<span class="hljs-string">&quot;test&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>pprint(metrics)
{<span class="hljs-string">&#x27;test_loss&#x27;</span>: <span class="hljs-number">11.05</span>,
<span class="hljs-string">&#x27;test_map&#x27;</span>: <span class="hljs-number">0.2827</span>,
<span class="hljs-string">&#x27;test_map_50&#x27;</span>: <span class="hljs-number">0.4193</span>,
<span class="hljs-string">&#x27;test_map_75&#x27;</span>: <span class="hljs-number">0.2913</span>,
<span class="hljs-string">&#x27;test_map_group&#x27;</span>: <span class="hljs-number">0.2092</span>,
<span class="hljs-string">&#x27;test_map_image&#x27;</span>: <span class="hljs-number">0.3334</span>,
<span class="hljs-string">&#x27;test_map_large&#x27;</span>: <span class="hljs-number">0.3763</span>,
<span class="hljs-string">&#x27;test_map_medium&#x27;</span>: <span class="hljs-number">0.2814</span>,
<span class="hljs-string">&#x27;test_map_rectangle&#x27;</span>: <span class="hljs-number">0.2793</span>,
<span class="hljs-string">&#x27;test_map_small&#x27;</span>: <span class="hljs-number">0.2021</span>,
<span class="hljs-string">&#x27;test_map_text&#x27;</span>: <span class="hljs-number">0.3089</span>,
<span class="hljs-string">&#x27;test_mar_1&#x27;</span>: <span class="hljs-number">0.0609</span>,
<span class="hljs-string">&#x27;test_mar_10&#x27;</span>: <span class="hljs-number">0.3403</span>,
<span class="hljs-string">&#x27;test_mar_100&#x27;</span>: <span class="hljs-number">0.5668</span>,
<span class="hljs-string">&#x27;test_mar_100_group&#x27;</span>: <span class="hljs-number">0.5979</span>,
<span class="hljs-string">&#x27;test_mar_100_image&#x27;</span>: <span class="hljs-number">0.6295</span>,
<span class="hljs-string">&#x27;test_mar_100_rectangle&#x27;</span>: <span class="hljs-number">0.5245</span>,
<span class="hljs-string">&#x27;test_mar_100_text&#x27;</span>: <span class="hljs-number">0.5151</span>,
<span class="hljs-string">&#x27;test_mar_large&#x27;</span>: <span class="hljs-number">0.7317</span>,
<span class="hljs-string">&#x27;test_mar_medium&#x27;</span>: <span class="hljs-number">0.5669</span>,
<span class="hljs-string">&#x27;test_mar_small&#x27;</span>: <span class="hljs-number">0.4138</span>}<!----></pre></div><!----> <p>Эти результаты можно улучшить, увеличив количество эпох или отрегулировав другие гиперпараметры в <a href="/docs/transformers/main/ru/main_classes/trainer#transformers.TrainingArguments">TrainingArguments</a>. Попробуйте!</p> <!--[1--><h2 class="relative group"><a id="inference" 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" href="#inference"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Вывод<!----></span></h2><!--]--><!----> <p>Теперь, когда вы дообучили модель, оценили её и загрузили на Hugging Face Hub, вы можете использовать её для инференса.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch
<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><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoImageProcessor, AutoModelForObjectDetection
<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>ds = load_dataset(<span class="hljs-string">&quot;merve/mobile-ui-design&quot;</span>, split=<span class="hljs-string">&quot;train&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>image = ds[<span class="hljs-number">5</span>][<span class="hljs-string">&quot;image&quot;</span>].convert(<span class="hljs-string">&quot;RGB&quot;</span>)<!----></pre></div><!----> <p>Загрузите модель и процессор изображений из Hugging Face Hub (пропустите, если они уже обучены в этой сессии):</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>model_repo = <span class="hljs-string">&quot;merve/rf_detr_finetuned_mobile_ui&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>image_processor = AutoImageProcessor.from_pretrained(model_repo)
<span class="hljs-meta">&gt;&gt;&gt; </span>model = AutoModelForObjectDetection.from_pretrained(model_repo)
<span class="hljs-meta">&gt;&gt;&gt; </span>model.<span class="hljs-built_in">eval</span>()<!----></pre></div><!----> <p>И обнаружение ограничивающих прямоугольников:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><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>], image.size[<span class="hljs-number">0</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 text <span class="hljs-keyword">with</span> confidence <span class="hljs-number">0.727</span> at location [<span class="hljs-number">324.02</span>, <span class="hljs-number">340.55</span>, <span class="hljs-number">339.52</span>, <span class="hljs-number">359.12</span>]
Detected rectangle <span class="hljs-keyword">with</span> confidence <span class="hljs-number">0.717</span> at location [<span class="hljs-number">39.97</span>, <span class="hljs-number">705.14</span>, <span class="hljs-number">335.93</span>, <span class="hljs-number">753.54</span>]
Detected text <span class="hljs-keyword">with</span> confidence <span class="hljs-number">0.702</span> at location [<span class="hljs-number">199.94</span>, <span class="hljs-number">473.66</span>, <span class="hljs-number">213.41</span>, <span class="hljs-number">490.6</span>]
Detected text <span class="hljs-keyword">with</span> confidence <span class="hljs-number">0.678</span> at location [<span class="hljs-number">153.14</span>, <span class="hljs-number">474.81</span>, <span class="hljs-number">165.33</span>, <span class="hljs-number">491.0</span>]
Detected text <span class="hljs-keyword">with</span> confidence <span class="hljs-number">0.675</span> at location [<span class="hljs-number">262.67</span>, <span class="hljs-number">718.28</span>, <span class="hljs-number">281.44</span>, <span class="hljs-number">740.81</span>]
Detected rectangle <span class="hljs-keyword">with</span> confidence <span class="hljs-number">0.655</span> at location [<span class="hljs-number">143.57</span>, <span class="hljs-number">242.51</span>, <span class="hljs-number">214.32</span>, <span class="hljs-number">274.26</span>]
Detected text <span class="hljs-keyword">with</span> confidence <span class="hljs-number">0.653</span> at location [<span class="hljs-number">298.68</span>, <span class="hljs-number">637.77</span>, <span class="hljs-number">345.68</span>, <span class="hljs-number">656.26</span>]<!----></pre></div><!----> <p>Построим график результата:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>draw = ImageDraw.Draw(image)
<span class="hljs-meta">&gt;&gt;&gt; </span>colors = {<span class="hljs-string">&quot;group&quot;</span>: <span class="hljs-string">&quot;blue&quot;</span>, <span class="hljs-string">&quot;image&quot;</span>: <span class="hljs-string">&quot;green&quot;</span>, <span class="hljs-string">&quot;rectangle&quot;</span>: <span class="hljs-string">&quot;red&quot;</span>, <span class="hljs-string">&quot;text&quot;</span>: <span class="hljs-string">&quot;orange&quot;</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> x, y, x2, y2 = <span class="hljs-built_in">tuple</span>(box)
<span class="hljs-meta">... </span> label_name = model.config.id2label[label.item()]
<span class="hljs-meta">... </span> color = colors.get(label_name, <span class="hljs-string">&quot;red&quot;</span>)
<span class="hljs-meta">... </span> draw.rectangle((x, y, x2, y2), outline=color, width=<span class="hljs-number">2</span>)
<span class="hljs-meta">... </span> draw.text((x, y), <span class="hljs-string">f&quot;<span class="hljs-subst">{label_name}</span> <span class="hljs-subst">{score:<span class="hljs-number">.2</span>f}</span>&quot;</span>, fill=color)
<span class="hljs-meta">&gt;&gt;&gt; </span>image<!----></pre></div><!----> <div class="flex justify-center"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/mobile_ui_result_5.png" alt="Object detection result on a cart screen"/></div> <div class="flex justify-center"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/mobile_ui_result_50.png" alt="Object detection result on a followers screen"/></div> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/transformers/blob/main/docs/source/en/tasks/object_detection.md" target="_blank"><svg class="mr-1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M31,16l-7,7l-1.41-1.41L28.17,16l-5.58-5.59L24,9l7,7z"></path><path d="M1,16l7-7l1.41,1.41L3.83,16l5.58,5.59L8,23l-7-7z"></path><path d="M12.419,25.484L17.639,6.552l1.932,0.518L14.351,26.002z"></path></svg><!----> <span><span class="underline">Update</span> on GitHub</span></a><!----> <p></p><!--]--><!----><!--]--><!--]--><!--]--> <!--[-1--><!--]--><!--]-->
<script>
{
__sveltekit_1m6yd5j = {
base: "/docs/transformers/main/en",
assets: "/docs/transformers/main/en"
};
const element = document.currentScript.parentElement;
Promise.all([
import("/docs/transformers/main/en/_app/immutable/entry/start.DYIO-UII.js"),
import("/docs/transformers/main/en/_app/immutable/entry/app.D2_KizbC.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 756],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
98.6 kB
·
Xet hash:
26dfe1ef1d867d9897d6a239050746759fe8e3674ce7416db89e04bbeb02b9aa

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.