Buckets:

hf-doc-build/doc / transformers /main /vi /tasks /object_detection.html
mishig's picture
download
raw
94.8 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Phát hiện đối tượng&quot;,&quot;local&quot;:&quot;object-detection&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Tải bộ dữ liệu 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;Tiền xử lý dữ liệu&quot;,&quot;local&quot;:&quot;preprocess-the-data&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Tăng cường dữ liệu&quot;,&quot;local&quot;:&quot;data-augmentation&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Chuẩn bị hàm để tính mAP&quot;,&quot;local&quot;:&quot;preparing-function-to-compute-map&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Huấn luyện mô hình phát hiện&quot;,&quot;local&quot;:&quot;training-the-detection-model&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Đánh giá&quot;,&quot;local&quot;:&quot;evaluate&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Suy luận&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><!---->Phát hiện đối tượng<!----></span></h1><!--]--><!----> <p>Phát hiện đối tượng là tác vụ thị giác máy tính nhằm phát hiện các thực thể (chẳng hạn như con người, tòa nhà hoặc ô tô) trong một hình ảnh. Mô hình phát hiện đối tượng nhận hình ảnh làm đầu vào và xuất ra
tọa độ của các khung bao (bounding box) cùng nhãn liên quan của các đối tượng được phát hiện. Một hình ảnh có thể chứa nhiều đối tượng,
mỗi đối tượng có khung bao và nhãn riêng (ví dụ: có thể có một ô tô và một tòa nhà), và mỗi đối tượng có
thể xuất hiện ở các phần khác nhau của hình ảnh (ví dụ: hình ảnh có thể có nhiều ô tô).
Tác vụ này thường được sử dụng trong lái xe tự động để phát hiện các vật thể như người đi bộ, biển báo đường và đèn giao thông.
Các ứng dụng khác bao gồm đếm số lượng đối tượng trong hình ảnh, tìm kiếm hình ảnh và nhiều hơn nữa.</p> <p>Trong hướng dẫn này, bạn sẽ học cách:</p> <ol><li>Tinh chỉnh <a href="https://huggingface.co/Roboflow/rf-detr-medium" rel="nofollow">RF-DETR</a> trên bộ dữ liệu <a href="https://huggingface.co/datasets/merve/mobile-ui-design" rel="nofollow">mobile-ui-design</a> để phát hiện các phần tử giao diện người dùng trong ảnh chụp màn hình ứng dụng di động.</li> <li>Sử dụng mô hình đã tinh chỉnh của bạn để suy luận.</li></ol> <blockquote class="tip"><p>Để xem tất cả các kiến trúc và checkpoint tương thích với tác vụ này, chúng tôi khuyến nghị bạn kiểm tra <a href="https://huggingface.co/tasks/object-detection" rel="nofollow">trang tác vụ</a></p><!----></blockquote><!----> <p>Trước khi bắt đầu, hãy đảm bảo bạn đã cài đặt tất cả các thư viện cần thiết:</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> Đã sao chép</div><!----></button><!----></div> <pre class="language-bash "><!---->pip install -q datasets transformers accelerate timm trackio torchmetrics pycocotools<!----></pre></div><!----> <p>Bạn sẽ sử dụng 🤗 Datasets để tải một bộ dữ liệu từ Hugging Face Hub và 🤗 Transformers để huấn luyện mô hình của bạn.</p> <p>Chúng tôi khuyến khích bạn chia sẻ mô hình của mình với cộng đồng. Đăng nhập vào tài khoản Hugging Face của bạn để tải lên Hub.
Khi được yêu cầu, nhập token của bạn để đăng nhậ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> Đã sao chép</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>Định nghĩa các hằng số toàn cục, cụ thể là tên mô hình và kích thước ảnh. Bài hướng dẫn này sử dụng RF-DETR, nhưng bạn có thể chọn bất kỳ mô hình phát hiện đối tượng nào trong 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> Đã sao chép</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><!---->Tải bộ dữ liệu mobile-ui-design<!----></span></h2><!--]--><!----> <p>Bộ dữ liệu <a href="https://huggingface.co/datasets/merve/mobile-ui-design" rel="nofollow">mobile-ui-design</a> chứa các ảnh chụp màn hình ứng dụng di động với chú thích để phát hiện các thành phần giao diện người dùng như văn bản, hình ảnh, hình chữ nhật và nhóm.</p> <p>Bắt đầu bằng cách tải bộ dữ liệu và trích xuất nhãn danh mục. Bộ dữ liệu đã có các phần chia (splits).</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> Đã sao chép</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>Bộ dữ liệu sử dụng tên danh mục dạng chuỗi và các hộp bao quanh (bounding box) ở định dạng COCO <code>(x, y, w, h)</code>. Hãy chuyển đổi các danh mục thành id dạng số nguyên, tính toán diện tích và lọc bỏ các hộp bao quanh suy biến trước khi huấn luyện:</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> Đã sao chép</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><!---->Tiền xử lý dữ liệu<!----></span></h2><!--]--><!----> <p><a href="/docs/transformers/main/vi/model_doc/auto#transformers.AutoImageProcessor">AutoImageProcessor</a> đảm nhận việc xử lý dữ liệu ảnh để tạo ra <code>pixel_values</code>, <code>pixel_mask</code> và <code>labels</code> để mô hình có thể huấn luyện. Bộ xử lý ảnh chịu trách nhiệm thay đổi kích thước, đệm và chuẩn hóa. Ngoài ra, bạn có thể tùy chọn thêm các phép tăng cường dữ liệu ngẫu nhiên (xem <a href="#data-augmentation">bên dưới</a>) để cải thiện khả năng tổng quát hó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> Đã sao chép</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> kỳ vọng chú thích ở định dạng COCO: <code>{'image_id': int, 'annotations': list[Dict]}</code>. Định dạng chú thích của từng ví dụ và để bộ xử lý lo phần còn lại:</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> Đã sao chép</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><!---->Tăng cường dữ liệu<!----></span></h3><!--]--><!----> <p>Biến đổi ở trên chỉ thay đổi kích thước và chuẩn hóa ảnh. Các phép tăng dữ liệu ngẫu nhiên áp dụng cho tập <strong>đào tạo</strong> thường cải thiện khả năng tổng quát hóa, trong khi tập xác thực nên giữ nguyên không tăng dữ liệu để đảm bảo đánh giá mang tính tất định. Một lựa chọn phổ biến là <a href="https://albumentations.ai/" rel="nofollow">Albumentations</a>, công cụ tăng dữ liệu cho cả ảnh và các hộp bao quanh cùng lúc. Hãy định nghĩa một pipeline với <code>bbox_params</code> để các hộp được biến đổi nhất quán với ảnh, sau đó tính lại diện tích từ các hộp đã tăng dữ liệu:</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> Đã sao chép</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>Áp dụng biến đổi tăng cường chỉ cho phần chia huấn luyện, và giữ nguyên <code>transform_fn</code> cho phần kiểm tra:</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> Đã sao chép</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>Tạo một <code>collate_fn</code> tùy chỉnh để nhóm các hình ảnh thành một lô:</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> Đã sao chép</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><!---->Chuẩn bị hàm để tính mAP<!----></span></h2><!--]--><!----> <p>Các mô hình phát hiện đối tượng thường được đánh giá bằng một bộ <a href="https://cocodataset.org/#detection-eval">các chỉ số kiểu COCO</a>. Chúng ta sẽ sử dụng <code>torchmetrics</code> để tính toán các chỉ số <code>mAP</code> (độ chính xác trung bình) và <code>mAR</code> (độ hồi tưởng trung bình) và sẽ bọc chúng vào hàm <code>compute_metrics</code> để sử dụng trong <a href="/docs/transformers/main/vi/main_classes/trainer#transformers.Trainer">Trainer</a> cho việc đánh giá.</p> <p>Định dạng trung gian của các hộp được sử dụng cho huấn luyện là <code>YOLO</code> (đã chuẩn hóa) nhưng chúng ta sẽ tính toán các chỉ số cho các hộp ở định dạng <code>Pascal VOC</code> (tuyệt đối) để xử lý đúng diện tích của các hộp. Hãy định nghĩa một hàm chuyển đổi các hộp bao quanh sang định dạng <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> Đã sao chép</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>Sau đó, trong hàm <code>compute_metrics</code>, chúng ta thu thập các hộp bao <code>predicted</code> và <code>target</code>, điểm số và nhãn từ kết quả của vòng lặp đánh giá, rồi truyền chúng vào hàm chấm điểm.</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> Đã sao chép</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><!---->Huấn luyện mô hình phát hiện<!----></span></h2><!--]--><!----> <p>Bạn đã hoàn thành phần lớn công việc nặng nhọc trong các phần trước, vì vậy giờ bạn đã sẵn sàng để huấn luyện mô hình của mình!
Các hình ảnh trong bộ dữ liệu này vẫn khá lớn, ngay cả sau khi đã thay đổi kích thước. Điều này có nghĩa là việc tinh chỉnh mô hình này sẽ
yêu cầu ít nhất một GPU.</p> <p>Quá trình huấn luyện bao gồm các bước sau:</p> <ol><li>Tải mô hình bằng <a href="/docs/transformers/main/vi/model_doc/auto#transformers.AutoModelForObjectDetection">AutoModelForObjectDetection</a> sử dụng cùng checkpoint như trong tiền xử lý.</li> <li>Định nghĩa các siêu tham số huấn luyện của bạn trong <a href="/docs/transformers/main/vi/main_classes/trainer#transformers.TrainingArguments">TrainingArguments</a>.</li> <li>Truyền các đối số huấn luyện vào <a href="/docs/transformers/main/vi/main_classes/trainer#transformers.Trainer">Trainer</a> cùng với mô hình, tập dữ liệu, bộ xử lý ảnh và bộ sắp xếp dữ liệu.</li> <li>Gọi <a href="/docs/transformers/main/vi/main_classes/trainer#transformers.Trainer.train">train()</a> để tinh chỉnh mô hình của bạn.</li></ol> <p>Khi tải mô hình từ cùng checkpoint mà bạn đã dùng cho tiền xử lý, hãy nhớ truyền các bản đồ <code>label2id</code> và <code>id2label</code> mà bạn đã tạo trước đó từ metadata của tập dữ liệu. Ngoài ra, chúng ta chỉ định <code>ignore_mismatched_sizes=True</code> để thay thế đầu phân loại hiện có bằng một đầu mới.</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> Đã sao chép</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>Trong <a href="/docs/transformers/main/vi/main_classes/trainer#transformers.TrainingArguments">TrainingArguments</a>, hãy dùng <code>output_dir</code> để chỉ định nơi lưu mô hình của bạn, sau đó cấu hình các siêu tham số theo ý bạn. Với <code>num_train_epochs=5</code>, quá trình huấn luyện sẽ mất khoảng 35 phút trên GPU A100; hãy tăng số epoch để đạt kết quả tốt hơn.</p> <p>Lưu ý quan trọng:</p> <ul><li>Không xóa các cột không được sử dụng vì điều này sẽ làm mất cột ảnh. Nếu không có cột ảnh, bạn
không thể tạo <code>pixel_values</code>. Vì lý do này, hãy đặt <code>remove_unused_columns</code> thành <code>False</code>.</li> <li>Đặt <code>eval_do_concat_batches=False</code> để có kết quả đánh giá chính xác. Các hình ảnh có số lượng hộp mục tiêu khác nhau, nếu các lô được nối lại, chúng ta sẽ không thể xác định hộp nào thuộc về hình ảnh cụ thể nào.</li></ul> <p>Nếu bạn muốn chia sẻ mô hình của mình bằng cách đẩy lên Hub, hãy đặt <code>push_to_hub</code> thành <code>True</code> (bạn phải đã đăng nhập vào Hugging Face để tải lên mô hình của mình).</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> Đã sao chép</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>Cuối cùng, hãy kết hợp tất cả lại và gọi <a href="/docs/transformers/main/vi/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> Đã sao chép</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, Epoch 5/5]</div> <table border="1" class="dataframe"><thead><tr style="text-align: left;"><th>Epoch</th><th>Mất huấn luyện</th><th>Loss kiểm định</th><th>Bản đồ</th><th>Map 50</th><th>Map 75</th><th>Map nhỏ</th><th>Bản đồ Medium</th><th>Map Large</th><th>Ngày 1 tháng 3</th><th>10 tháng 3</th><th>Mar 100</th><th>Mar Small</th><th>Tháng Ba Trung bình</th><th>Mar Large</th><th>Nhóm Map</th><th>Nhóm Mar 100</th><th>Bản đồ hình ảnh</th><th>Ảnh Mar 100</th><th>Map Rectangle</th><th>Mar 100 Rectangle</th><th>Bản đồ văn bản</th><th>Mar 100 Text</th></tr></thead><tbody><tr><td>1</td><td>Không có nhật ký</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>Không có nhật ký</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>Không có nhật ký</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>Không có nhật ký</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>Nếu bạn đã đặt <code>push_to_hub</code> thành <code>True</code> trong <code>training_args</code>, các checkpoint huấn luyện sẽ được đẩy lên Hugging Face Hub. Khi quá trình huấn luyện hoàn tất, hãy đẩy mô hình cuối cùng lên Hub bằng cách gọi phương thức <a href="/docs/transformers/main/vi/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> Đã sao chép</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><!---->Đánh giá<!----></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> Đã sao chép</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>Các kết quả này có thể được cải thiện thêm bằng cách tăng số lượng epoch hoặc điều chỉnh các siêu tham số khác trong <a href="/docs/transformers/main/vi/main_classes/trainer#transformers.TrainingArguments">TrainingArguments</a>. Hãy thử ngay!</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><!---->Suy luận<!----></span></h2><!--]--><!----> <p>Giờ đây, khi bạn đã tinh chỉnh một mô hình, đánh giá nó và tải nó lên Hugging Face Hub, bạn có thể sử dụng nó để suy luận.</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> Đã sao chép</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>Tải model và image processor từ Hugging Face Hub (bỏ qua nếu đã được huấn luyện trong phiên này):</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> Đã sao chép</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>Và phát hiện các hộp bao:</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> Đã sao chép</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>Hãy vẽ kết quả:</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> Đã sao chép</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:
94.8 kB
·
Xet hash:
033cebe712353233c7364c29cda88af48c63b5b736b0d5aed22219e7746b8e16

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