Tổng quan về dataset
Ultralytics hỗ trợ các bộ dữ liệu cho tác vụ thị giác máy tính như phát hiện, phân đoạn instance, phân đoạn ngữ nghĩa, ước tính độ sâu, phân loại, ước tính tư thế và bounding box định hướng (OBB). Dưới đây là danh sách các bộ dữ liệu chính của Ultralytics, tiếp theo là phần tóm tắt từng tác vụ thị giác máy tính cùng các bộ dữ liệu tương ứng. Chế độ Track chạy trên các model phát hiện, phân đoạn, tư thế và OBB mà không cần huấn luyện riêng cho tracker; xem bộ dữ liệu theo dõi.
Xem: Tổng quan về dataset của Ultralytics
Phát hiện đối tượng#
Phát hiện vật thể bằng bounding box là kỹ thuật thị giác máy tính giúp phát hiện và xác định vị trí vật thể trong ảnh bằng cách vẽ một bounding box quanh mỗi vật thể.
- African-wildlife: Dataset gồm hình ảnh động vật hoang dã châu Phi, bao gồm trâu, voi, tê giác và ngựa vằn.
- Argoverse: Dataset chứa dữ liệu theo dõi 3D và dự báo chuyển động trong môi trường đô thị, kèm chú thích phong phú.
- Khối u não: Dataset dùng để phát hiện khối u trong ảnh MRI não, với các khối u được gán nhãn bằng bounding box trong một class duy nhất.
- COCO: Common Objects in Context (COCO) là dataset quy mô lớn về phát hiện, phân đoạn và tạo chú thích cho vật thể, với 80 danh mục vật thể.
- COCO8: Tập con nhỏ gồm 8 ảnh đầu tiên của COCO train2017, trong đó 4 ảnh dùng để huấn luyện và 4 ảnh để xác thực, phù hợp cho các bài kiểm tra nhanh.
- COCO8-Grayscale: Phiên bản ảnh thang độ xám của COCO8, được tạo bằng cách chuyển RGB sang thang độ xám, hữu ích để đánh giá model một kênh.
- COCO8-Multispectral: Phiên bản đa phổ 10 kênh của COCO8, được tạo bằng cách nội suy các bước sóng RGB, hữu ích để đánh giá model có nhận biết phổ.
- COCO12-Formats: Dataset kiểm thử gồm 12 ảnh, bao quát 12 định dạng ảnh được hỗ trợ (AVIF, BMP, DNG, HEIC, JP2, JPEG, JPG, MPO, PNG, TIF, TIFF, WebP) để xác thực quy trình tải ảnh.
- COCO128: Tập con nhỏ gồm 128 ảnh đầu tiên của COCO train2017, phù hợp cho kiểm thử.
- Construction-PPE: Dataset gồm hình ảnh công trường xây dựng, được gán nhãn các thiết bị an toàn thiết yếu như mũ bảo hộ, áo phản quang, găng tay, ủng và kính bảo hộ, cùng nhãn cho thiết bị còn thiếu; hỗ trợ phát triển model AI nhằm đảm bảo tuân thủ quy định và bảo vệ người lao động.
- Global Wheat 2020: Dataset gồm hình ảnh bông lúa mì dành cho Global Wheat Challenge 2020.
- HomeObjects-3K: Dataset gồm các cảnh trong nhà được chú thích, với 12 đồ vật gia dụng phổ biến; lý tưởng để phát triển và kiểm thử model thị giác máy tính trong hệ thống nhà thông minh, robot và thực tế tăng cường.
- KITTI: Dataset lái xe tự hành nổi tiếng, có đầu vào stereo, LiDAR và GPS/IMU, được sử dụng để phát hiện vật thể 2D trong nhiều cảnh đường sá khác nhau.
- LVIS: Dataset quy mô lớn về phát hiện và phân đoạn đối tượng, với 1.203 danh mục vật thể.
- Medical-pills: Dataset chứa ảnh thuốc viên được gán nhãn, được thiết kế để hỗ trợ các tác vụ như kiểm soát chất lượng dược phẩm, phân loại và đảm bảo tuân thủ tiêu chuẩn ngành.
- Objects365: Dataset chất lượng cao, quy mô lớn về phát hiện vật thể, với 365 danh mục vật thể và hơn 1,7 triệu ảnh được chú thích.
- Open Images V7: Bộ dữ liệu quy mô lớn của Google với 601 lớp, 1,7 triệu hình ảnh huấn luyện và 42 nghìn hình ảnh đánh giá.
- RF100: Benchmark phát hiện vật thể đa dạng gồm 100 dataset trải rộng trên bảy miền hình ảnh, phục vụ đánh giá model toàn diện.
- Signature: Dataset gồm hình ảnh nhiều loại tài liệu với chữ ký được chú thích, hỗ trợ nghiên cứu xác minh tài liệu và phát hiện gian lận.
- SKU-110K: Dataset phục vụ phát hiện vật thể dày đặc trong môi trường bán lẻ, gồm hơn 11 nghìn ảnh và 1,7 triệu bounding box.
- TT100K: Dataset biển báo giao thông Tsinghua-Tencent 100K với 16.817 ảnh đường phố thuộc 221 danh mục biển báo.
- Ultralytics Benchmark: Bộ benchmark chính thức gồm 37 tập dữ liệu phát hiện được tuyển chọn trong các lĩnh vực y tế, hàng không, công nghiệp, bán lẻ và các lĩnh vực khác, với quy trình cố định để đo lường khả năng tổng quát hóa của model trong thực tế.
- VisDrone: Dataset chứa dữ liệu phát hiện vật thể và theo dõi nhiều vật thể từ hình ảnh do drone ghi lại, với hơn 10 nghìn ảnh và chuỗi video.
- VOC: Dataset Pascal Visual Object Classes (VOC) phục vụ phát hiện và phân đoạn vật thể, với 20 lớp vật thể và hơn 21 nghìn ảnh.
- xView: Dataset phát hiện vật thể trong ảnh chụp từ trên cao, với 60 danh mục vật thể và hơn 1 triệu vật thể được chú thích.
Phân đoạn đối tượng#
Phân đoạn đối tượng là kỹ thuật thị giác máy tính giúp nhận diện và xác định vị trí vật thể trong ảnh ở cấp độ pixel. Khác với phân đoạn ngữ nghĩa vốn chỉ phân loại từng pixel, phân đoạn đối tượng phân biệt các cá thể khác nhau thuộc cùng một lớp.
- Carparts-seg: Dataset được thiết kế chuyên biệt để nhận diện các bộ phận xe, đáp ứng nhu cầu thiết kế, sản xuất và nghiên cứu. Dataset hỗ trợ cả tác vụ phát hiện lẫn phân đoạn vật thể.
- COCO: Dataset quy mô lớn được thiết kế cho các tác vụ phát hiện, phân đoạn và tạo chú thích, với hơn 200 nghìn ảnh được gán nhãn.
- COCO8-seg: Dataset nhỏ dành cho các tác vụ phân đoạn đối tượng, gồm tập con 8 ảnh COCO có chú thích phân đoạn.
- COCO128-seg: Dataset nhỏ dành cho các tác vụ phân đoạn đối tượng, gồm tập con 128 ảnh COCO có chú thích phân đoạn.
- Crack-seg: Dataset được xây dựng chuyên biệt để phát hiện vết nứt trên đường và tường, phù hợp cho cả tác vụ phát hiện lẫn phân đoạn vật thể.
- Package-seg: Dataset được thiết kế để nhận diện kiện hàng trong kho hoặc môi trường công nghiệp, phù hợp cho cả ứng dụng phát hiện lẫn phân đoạn vật thể.
Phân đoạn ngữ nghĩa#
Phân đoạn ngữ nghĩa gán nhãn lớp cho từng pixel trong hình ảnh, tạo bản đồ cảnh dày đặc cho các ứng dụng như xe tự hành, phân tích cảnh và lập bản đồ lớp phủ đất.
- Cityscapes: Dataset phân đoạn ngữ nghĩa cảnh đường phố đô thị với 19 lớp huấn luyện.
- Cityscapes8: Tập con Cityscapes gọn nhẹ gồm 8 ảnh, dùng để kiểm tra nhanh quy trình phân đoạn ngữ nghĩa.
- ADE20K: Dataset phân tích cảnh với 150 lớp ngữ nghĩa.
Ước lượng độ sâu#
Ước tính độ sâu đơn ảnh dự đoán bản đồ độ sâu theo từng pixel, tính bằng mét, từ một hình ảnh RGB duy nhất; hỗ trợ tái tạo cảnh 3D, điều hướng robot và các ứng dụng AR/VR.
- Depth8: Tập con SUN RGB-D gọn nhẹ gồm 8 ảnh, dùng để kiểm tra nhanh quy trình.
- ARKitScenes: Dữ liệu RGB-D trong nhà thực tế được ghi lại bằng LiDAR của Apple ARKit, là nguồn dữ liệu huấn luyện thực tế lớn nhất.
- SUN RGB-D: Các cảnh trong nhà thực tế được ghi lại bằng bốn cảm biến RGB-D khác nhau.
- DIODE: Dữ liệu độ sâu dày đặc trong nhà và ngoài trời, thu thập bằng máy quét laser cấp độ khảo sát.
- Hypersim: Các cảnh trong nhà tổng hợp chân thực như ảnh chụp, với độ sâu hoàn hảo ở từng pixel.
- TartanAir: Môi trường AirSim tổng hợp với dữ liệu độ sâu dày đặc ở khoảng cách ~80 m.
- Virtual KITTI 2: Tái tạo tổng hợp các cảnh lái xe KITTI với dữ liệu độ sâu dày đặc.
- KITTI: Các cảnh lái xe tự hành ngoài trời trong thế giới thực với dữ liệu độ sâu LiDAR Velodyne, đồng thời là benchmark KITTI Eigen.
- ImageNet (gán nhãn giả): Ảnh ImageNet-1K với nhãn giả từ Depth Anything 3 để chưng cất model.
- NYU Depth V2: Benchmark độ sâu trong nhà tiêu chuẩn, được ghi lại bằng Microsoft Kinect v1.
- ETH3D: Benchmark máy quét laser độ chính xác cao trong nhà và ngoài trời.
- Make3D: Benchmark khuôn viên ngoài trời có phân phối khác biệt.
- iBims-1: Benchmark trong nhà chất lượng cao dành cho biên độ sâu và bề mặt phẳng.
Phân loại#
Phân loại ảnh là tác vụ thị giác máy tính nhằm phân loại ảnh thành một hoặc nhiều lớp hay danh mục được xác định trước dựa trên nội dung hình ảnh.
- Caltech 101: Dataset gồm ảnh thuộc 101 danh mục vật thể, phục vụ các tác vụ phân loại ảnh.
- Caltech 256: Phiên bản mở rộng của Caltech 101 với 256 danh mục vật thể và hình ảnh thách thức hơn.
- CIFAR-10: Dataset gồm 60 nghìn ảnh màu kích thước 32x32 thuộc 10 lớp, mỗi lớp có 6 nghìn ảnh.
- CIFAR-100: Phiên bản mở rộng của CIFAR-10 với 100 danh mục vật thể và 600 ảnh mỗi lớp.
- Fashion-MNIST: Dataset gồm 70.000 ảnh thang độ xám thuộc 10 danh mục thời trang, phục vụ các tác vụ phân loại ảnh.
- ImageNet: Dataset quy mô lớn phục vụ phát hiện vật thể và phân loại ảnh, với hơn 14 triệu ảnh và 20.000 danh mục.
- ImageNet-10: Tập con nhỏ của ImageNet gồm 10 danh mục, giúp thử nghiệm và kiểm thử nhanh hơn.
- Imagenette: Tập con nhỏ của ImageNet gồm 10 lớp dễ phân biệt, giúp huấn luyện và kiểm thử nhanh hơn.
- Imagewoof: Tập con ImageNet khó hơn, gồm 10 danh mục giống chó, phục vụ các tác vụ phân loại ảnh.
- MNIST: Dataset gồm 70.000 ảnh thang độ xám về chữ số viết tay, phục vụ các tác vụ phân loại ảnh.
- MNIST160: 8 ảnh đầu tiên của mỗi chữ số (0-9) từ cả tập huấn luyện và tập kiểm thử MNIST. Dataset có tổng cộng 160 ảnh.
Ước lượng tư thế#
Ước tính tư thế là kỹ thuật xác định tư thế của một đối tượng so với camera hoặc hệ tọa độ thế giới. Kỹ thuật này bao gồm việc xác định keypoint hoặc khớp trên đối tượng, đặc biệt là người hoặc động vật.
- COCO: Dataset quy mô lớn có chú thích tư thế người, được thiết kế cho các tác vụ ước tính tư thế.
- COCO8-pose: Dataset nhỏ dành cho các tác vụ ước tính tư thế, gồm tập con 8 ảnh COCO có chú thích tư thế người.
- Dog-pose: Dataset toàn diện gồm khoảng 8.500 ảnh tập trung vào chó, được chú thích 24 điểm then chốt cho mỗi con chó và thiết kế cho các tác vụ ước tính tư thế.
- Hand-Keypoints: Bộ dữ liệu gồm hơn 26.000 hình ảnh tập trung vào bàn tay người, được gán nhãn 21 keypoint cho mỗi bàn tay và thiết kế cho các tác vụ ước tính tư thế.
- Tiger-pose: Dataset gọn gồm 263 ảnh tập trung vào hổ, được chú thích 12 điểm then chốt cho mỗi con hổ để phục vụ các tác vụ ước tính tư thế.
BBox định hướng (OBB)#
Bounding box định hướng (OBB) là phương pháp thị giác máy tính để phát hiện vật thể nghiêng trong ảnh bằng bounding box xoay, thường được áp dụng cho ảnh hàng không và ảnh vệ tinh. Khác với bounding box truyền thống, OBB có thể khớp với vật thể ở nhiều hướng khác nhau tốt hơn.
- DOTA-v2: Dataset ảnh hàng không OBB phổ biến với 1,7 triệu đối tượng và 11.268 ảnh.
- DOTA8: Tập con nhỏ gồm 8 ảnh đầu tiên của tập chia DOTAv1, trong đó 4 ảnh dùng để huấn luyện và 4 ảnh để xác thực, phù hợp cho các bài kiểm tra nhanh.
- DOTA128: Tập con gồm 128 hình ảnh của DOTAv1, dùng cho cả huấn luyện và đánh giá, tạo sự cân bằng hợp lý giữa quy mô và tính đa dạng để kiểm thử các model OBB.
Đóng góp dataset mới#
Việc đóng góp dataset mới gồm một số bước để đảm bảo dataset tương thích tốt với hạ tầng hiện có. Dưới đây là các bước cần thực hiện:
Xem: Cách đóng góp cho dataset của Ultralytics
Các bước đóng góp dataset mới#
-
Thu thập hình ảnh: Tập hợp hình ảnh thuộc bộ dữ liệu. Bạn có thể thu thập hình ảnh từ nhiều nguồn, chẳng hạn như cơ sở dữ liệu công khai hoặc bộ sưu tập của riêng mình.
-
Gán nhãn hình ảnh: Gán nhãn các hình ảnh này bằng bounding box, segment hoặc keypoint, tùy theo tác vụ.
-
Xuất chú thích: Chuyển đổi các chú thích này sang định dạng tệp YOLO
*.txtmà Ultralytics hỗ trợ. -
Sắp xếp dataset: Sắp xếp dataset theo cấu trúc thư mục chính xác. Bạn cần có các thư mục cấp cao nhất
images/vàlabels/, bên trong mỗi thư mục là các thư mục contrain/vàval/.dataset/ ├── images/ │ ├── train/ │ └── val/ └── labels/ ├── train/ └── val/ -
Tạo tệp
data.yaml: Trong thư mục gốc của dataset, hãy tạo tệpdata.yamlmô tả dataset, các lớp và thông tin cần thiết khác. -
Tối ưu hóa ảnh (Tùy chọn): Nếu muốn giảm kích thước dataset để xử lý hiệu quả hơn, bạn có thể tối ưu hóa ảnh bằng đoạn code dưới đây. Bước này không bắt buộc, nhưng được khuyến nghị để giảm dung lượng dataset và tăng tốc độ tải xuống.
-
Nén dataset: Nén toàn bộ thư mục dataset thành tệp zip.
-
Tài liệu và PR: Tạo một trang tài liệu mô tả dataset của bạn và cách dataset tích hợp với framework hiện có. Sau đó, gửi Pull Request (PR). Tham khảo Hướng dẫn đóng góp cho Ultralytics để biết thêm chi tiết về cách gửi PR.
Ví dụ mã để tối ưu hóa và nén dataset#
from pathlib import Path
from ultralytics.data.utils import compress_one_image
from ultralytics.utils.downloads import zip_directory
# Xác định thư mục dataset
path = Path("path/to/dataset")
# Tối ưu hóa ảnh trong dataset (không bắt buộc)
for f in path.rglob("*.jpg"):
compress_one_image(f)
# Nén dataset thành 'path/to/dataset.zip'
zip_directory(path)Bằng cách làm theo các bước này, bạn có thể đóng góp một dataset mới tích hợp tốt với cấu trúc hiện có của Ultralytics.
Câu hỏi thường gặp#
Ultralytics hỗ trợ nhiều loại dataset cho phát hiện đối tượng, bao gồm:
- COCO: Dataset quy mô lớn về phát hiện đối tượng, phân đoạn và tạo chú thích, với 80 danh mục đối tượng.
- LVIS: Dataset đa dạng với 1.203 danh mục đối tượng, được thiết kế cho các bài toán phát hiện và phân đoạn đối tượng chi tiết hơn.
- Argoverse: Dataset chứa dữ liệu theo dõi 3D và dự báo chuyển động trong môi trường đô thị, kèm chú thích phong phú.
- VisDrone: Dataset gồm dữ liệu phát hiện đối tượng và theo dõi đa đối tượng từ hình ảnh do drone ghi lại.
- SKU-110K: Dataset tập trung vào phát hiện đối tượng dày đặc trong môi trường bán lẻ, với hơn 11K ảnh.
Các bộ dữ liệu này hỗ trợ huấn luyện các model Ultralytics YOLO mạnh mẽ cho nhiều ứng dụng phát hiện đối tượng.
Đóng góp dataset mới gồm một số bước sau:
- Thu thập ảnh: Tập hợp ảnh từ cơ sở dữ liệu công khai hoặc bộ sưu tập cá nhân.
- Gán nhãn ảnh: Tùy theo tác vụ, hãy gán bounding box, segment hoặc keypoint.
- Xuất nhãn: Chuyển đổi nhãn sang định dạng YOLO
*.txt. - Sắp xếp dataset: Sử dụng cấu trúc thư mục gồm các thư mục
images/vàlabels/, mỗi thư mục chứa các thư mục contrain/vàval/. - Tạo tệp
data.yaml: Thêm mô tả dataset, các class và thông tin liên quan khác. - Tối ưu hóa ảnh (không bắt buộc): Giảm kích thước dataset để tăng hiệu quả.
- Nén dataset: Nén dataset thành tệp zip.
- Tài liệu và PR: Mô tả dataset của bạn và gửi Pull Request theo Hướng dẫn đóng góp cho Ultralytics.
Truy cập Đóng góp dataset mới để xem hướng dẫn đầy đủ.
Ultralytics Platform cung cấp các tính năng quản lý và phân tích dataset, bao gồm:
- Quản lý bộ dữ liệu: Tải lên, sắp xếp và quản lý các bộ dữ liệu tại một nơi.
- Tích hợp huấn luyện tức thì: Sử dụng dataset đã tải lên trực tiếp để huấn luyện model mà không cần thiết lập thêm.
- Công cụ trực quan hóa: Khám phá và trực quan hóa ảnh cùng nhãn của dataset.
- Phân tích dataset: Nắm được thông tin chi tiết về phân bố và đặc điểm của dataset.
Dataset được chuyển thẳng từ khâu quản lý sang huấn luyện model trên cùng một nền tảng.
Các model Ultralytics YOLO cung cấp nhiều tính năng độc đáo cho các tác vụ thị giác máy tính:
- Hiệu năng thời gian thực: Khả năng suy luận và huấn luyện tốc độ cao cho các ứng dụng nhạy cảm về thời gian.
- Tính linh hoạt: Hỗ trợ phát hiện, phân đoạn instance, phân đoạn ngữ nghĩa, ước tính độ sâu, phân loại, ước tính pose và các tác vụ bounding box định hướng (OBB) trong một framework thống nhất.
- Model tiền huấn luyện: Truy cập các model tiền huấn luyện có hiệu năng cao cho nhiều ứng dụng, giúp giảm thời gian huấn luyện.
- Hỗ trợ cộng đồng rộng rãi: Cộng đồng năng động và tài liệu toàn diện hỗ trợ khắc phục sự cố và phát triển.
- Tích hợp dễ dàng: API đơn giản để tích hợp với các dự án và workflow hiện có.
Để tối ưu hóa và nén bộ dữ liệu thành ZIP bằng công cụ Ultralytics, hãy làm theo đoạn mã ví dụ sau:
Tối ưu hóa và nén datasetfrom pathlib import Path from ultralytics.data.utils import compress_one_image from ultralytics.utils.downloads import zip_directory # Xác định thư mục dataset path = Path("path/to/dataset") # Tối ưu hóa ảnh trong dataset (không bắt buộc) for f in path.rglob("*.jpg"): compress_one_image(f) # Nén dataset thành 'path/to/dataset.zip' zip_directory(path)Quy trình này giúp giảm kích thước bộ dữ liệu để lưu trữ hiệu quả hơn và tải xuống nhanh hơn.
Bình luận73
Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.
Fatima-khanjar
Hello, I hope you're doing well.
I have a question regarding the imgsz argument in YOLO (imgsz=224).
How exactly does the resizing process work internally? Specifically:
- Are images resized with padding to maintain aspect ratio?
- What if the original images are very small (e.g., 50×50)? Are they upscaled with padding, or just stretched to fit the target size?
- Does this resizing strategy affect model performance or accuracy?
Thanks in advance for your clarification!
gdenis82(đã chỉnh sửa)
Hi. Please tell me how I can balance the class weights in data.yaml for yolo11x-seg:
train: path/to/dataset/train/images val: path/to/dataset/val/images nc: 2 # number of classes names: [class 0, class 1] # list of class name cls_pw: [0.9, 0.1] or pos_weight: [0.9, 0.1]I did not find an exact understanding of how to do this.
Glenn JocherUltralytics(đã chỉnh sửa)@gdenis82 hello! Class weights like
cls_pworpos_weightare not defined within thedata.yamlfile itself.These parameters are typically hard-coded within your Python training script.
gdenis82
Hello. Good documentation. You're the best at it. Thank you. I looked at it again, found a lot of interesting and useful things, but I still haven't found the answer to this question. Here is a simple example with a train. What argument do I need to use to balance the class weights?
from ultralytics import YOLO # Load a model model = YOLO("yolo11x-seg.pt") # load a pretrained model (recommended for training) # Train the model with 2 GPUs results = model.train(data="data.yaml", epochs=100, imgsz=640, device=[0, 1])
Glenn JocherUltralytics@gdenis82 to handle class imbalance in YOLO11x-seg training, you have a few options:
-
Use the
clsparameter in the training function to adjust the classification loss weight:model.train(data="data.yaml", epochs=100, imgsz=640, device=[0, 1], cls=0.7) # Adjust overall classification loss weight -
For more granular control, you can create a custom configuration file to define class weights. The class weights are typically handled in the loss function, not directly in the data.yaml.
-
For severely imbalanced datasets, consider these practical approaches:
- Adjust your dataset sampling to balance class representation
- Use techniques like oversampling of minority classes or undersampling of majority classes
- Apply data augmentation more heavily to underrepresented classes
Class-specific weights aren't directly specified as a training argument in the current API. If you need very fine-grained control, you might need to modify the loss function implementation.
Does this help with your class balancing needs?
-
gdenis82
@glenn-jocher Thank you. Do I understand correctly that this approach sets a reduced total weight of the classification error and corrects only the overall component of the loss function. For ** the entire cluster analysis**, and not separately for each class. This is useful if we have a small data imbalance and all classes can be adjusted in the same way. If each class should have individual weights (depending on the classes shown in the image), what should be done?
# Determine the weights of the classes # Assume 3 classes: 0 - majority class, 1 - minority class, 2 - rare class weights = torch.tensor([0.5, 2.0, 3.0]) # The weights should be the inverse of the frequency of occurrence of classes.
Glenn JocherUltralytics(đã chỉnh sửa)@gdenis82 you're correct - the
clsparameter adjusts the overall classification loss weight, not individual class weights. For implementing individual class weights in YOLO, you would need to modify the loss function directly in the source code.The most straightforward approach would be to:
- Clone the Ultralytics repository
- Locate the loss implementation (typically in
ultralytics/utils/loss.py) - Modify the classification loss calculation to incorporate your custom class weights
- Use your modified version for training
For example, you might need to add something like:
# In the loss function where classification loss is calculated class_weights = torch.tensor([0.5, 2.0, 3.0], device=targets.device) cls_loss = cls_loss * class_weights[targets.long()]Alternatively, data-based approaches are often more practical:
- Oversampling underrepresented classes
- Augmenting minority classes more aggressively
- Using techniques like focal loss (a
FocalLossclass exists inultralytics/utils/loss.py, but it is not used by default)
These approaches often yield better results than direct weight modification and don't require source code changes.
gdenis82
@glenn-jocher Hello. Thanks for your patience and detailed explanation. I got the answer to my question.
D3RK0
Hi,
Introduction
For a couple of days now, I am trying to set YOLOv8 in classification mode in order to classify flowers in the images of the Oxford Flower dataset (i.e. https://www.robots.ox.ac.uk/~vgg/data/flowers/102/). I am using ImageNet pretrained weights to start my training.
The error
However, I am the obtaining error:
Dataset not found ⚠️, missing path C:\Users\ <'my_path'> \Oxford-Flower-dataset\oxford_flower.yaml, attempting download... Downloading https://ultralytics.com/assets/C://Users/ <'my_path'> /Oxford-Flower-dataset/oxford_flower.yaml.zip to 'C:\Users\ <'my_path'> \Oxford-Flower-dataset\oxford_flower.yaml.zip'...
My code
-
Creation of model object: model = YOLO("yolov8m-cls.pt")
-
Model.training: model.train(mode="classify", data=data_file_path, epochs=num_epochs, batch=batch_size, imgsz=256, lr0=lr, optimizer="AdamW", cos_lr=True, momentum=0.937, weight_decay=weight_decay)
-
Note that variable "data_file_path" is the path to my .yaml file I created for the Oxford Flower dataset
My yaml file
The content of my .yaml file is:
names:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9 ....
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102 nc: 102 path: C:/Users/ <'my_path'> /Oxford-Flower-dataset/jpg train: train/images train_label_dir: train/labels val: val/images val_label_dir: val/labels
Data directories
The directories of my data is exactly the way your colleague / member "pderrenger" describes it in her message of March 30th 2024. It looks like:
dataset/ ├── train/ │ ├── images/ │ └── labels.txt └── val/ ├── images/ └── labels.txt
Labels.txt content
The content of labels.txt is:
image_06734.txt 1 image_06735.txt 1 image_06737.txt 1 image_06742.txt 1 image_06743.txt 1 image_06745.txt 1 image_06746.txt 1 image_06748.txt 1 image_06751.txt 1 image_06752.txt 1 ....
Question
Why is it unable to find the data? What I am I missing
D3RK0
The dashes in "My yaml file" section has been automatically changed bullet points. That is not intended. So, bullet points in that section are dashes.
Glenn JocherUltralytics(đã chỉnh sửa)@D3RK0 it seems the issue is with the dataset path. For classification,
datashould be the path to the dataset root directory (not a YAML file), containingtrain/andval/(ortest/) folders with one subfolder per class. The.yamlyou created is not used for classification, which is why Ultralytics tried to download it. For more details, visit https://docs.ultralytics.com/datasets/classify/.1D3RK0
@glenn-jocher Thank you for your quick reply!
Testing directories as they are in the .yaml file
All the directories in my .yaml file should exist:
Note that the prepare_dataset.data_dir variable is created by using a simple dialog:
filedialog.askdirectory(title="Select the image data folder:").Folder structure
As indicated by your colleague, I am using the following structure:
dataset/ ├── train/ │ ├── images/ │ └── labels.txt └── val/ ├── images/ └── labels.txt
Is this structure correct?
Note that in the dataset folder (which is called, in my case, the jpg folder) are all the original .jpeg images files. Originally, the Oxford Flower dataset did not had this structure; all the image files are in jpg folder. Therefore, I created the folder structure you see above and copied the image files (via a script) to the train/images and val/images. But, I did not remove the original image files in the jpg folders. Could not removing the originals be the problem?
Creating the
data_file_pathvariableComparably, to create
data_file_pathvariable, I usedata_file_path = filedialog.askopenfilename(title="Please select the dataset .yaml dataset file for YOLOv8:").Directories in the .yaml file
In the .yaml file, do indicate the labels directory with the extension e.g. train/labels.txt?
Glenn JocherUltralytics(đã chỉnh sửa)It looks like the issue is the dataset layout. For classification, pass the dataset root directory as
data(not a YAML file), and make sure it containstrain/andval/folders with one subfolder per class (the folder name is the class label). Nolabelsdirectory or label files are used.1D3RK0(đã chỉnh sửa)
@glenn-jocher Thank you for your quick reply :-D
Clarification about the
pathkey directoryNote that the
pathkey is not literallyC:/Users/ <'my_path'> /Oxford-Flower-dataset/jpg. With<'my_path'>, I omitted part of the path for privacy. More realistically, it is likeC:/Users/my_several_folders/Oxford-Flower-dataset/jpg. I hope we are the same page on that :-) .Folder structure
You are saying: "The labels should be in a directory, not a single file." So, then the correct folder structure is not the way your colleague 'pderrenger' describes it; it is:
dataset/ ├── train/ │ ├── images/ │ └── labels/ └── val/ ├── images/ └── labels/
This is thus the expected folder structure, is it not? I have changed my folder structure to match with the expected folder, as described above. In my case, it is now:
Where the jpg folder is the root directory of my dataset and to which the aforementioned
pathkey in my .yaml file points to. The image files are in the train/images and val/images folders. Lastly, the labels.txt files are the train/labels and val/labels folders.The content of current .yaml file
names:
- 1
- 2
- 3 ...
- 100
- 101
- 102 nc: 102 path: C:/Users/derk_/Documents/Universiteit/IRP/Research_Project/Oxford-Flower-dataset/jpg train: train/images train_label_dir: train/labels val: val/images val_label_dir: val/labels
In summary
pathkeyThe
pathkey is approximatelyC:/Users/my_several_folders/Oxford-Flower-dataset/jpg. This is my root directory of my dataset.Current folder structure
The current folder structure is:
Changes I made
- I changed the folder structure
- I did not change the .yaml file content, because I can not see how that is wrong
Result of the changes
Changing the folder structure did not solve the problem. It is still unable to find the dataset.
Additional questions
Could you please be explicit about what the correct folder structure is? Could you please give an example of what a correct .yaml structure looks like, as this is not reported in the Ultralytics documentation (unless I missed it)?
Many thanks!
Glenn JocherUltralytics(đã chỉnh sửa)It seems the folder structure is causing the issue. For classification, no label files are needed: place the images of each class in a folder named after the class, inside
train/andval/. Then pass the dataset root directory asdata. For more details, please refer to the classification dataset guide.1D3RK0
@glenn-jocher Many thanks for your quick responses!
Changes
I changed my code from making the single
labels.txtfile to making individual label .txt files. It now looks like:At the top of image is part of the directory. Below there are the label .txt files. In bottom-left is example of the content of such label file.
Are the names of the label .txt file correct?
Result
Still the same dataset not found error :(
Glenn JocherUltralytics(đã chỉnh sửa)Each image's class is taken from the name of the folder it sits in, so no label files are needed for classification. Make sure your data is organized as
dataset/train/<class_name>/*.jpganddataset/val/<class_name>/*.jpg, and pass the dataset root directory asdata.D3RK0
@glenn-jocher Thanks for responding!
I have solved the previous problem. I have another problem, however.
Output by the YOLOv8 model
YAML file created at: C:/Users/derk_/Documents/Universiteit/IRP/Research_Project/Oxford-Flower-dataset/jpg\oxford_flower.yaml New https://pypi.org/project/ultralytics/8.3.28 available 😃 Update with 'pip install -U ultralytics' engine\trainer: task=classify, mode=train, model=yolov8m-cls.pt, data=C:/Users/derk_/Documents/Universiteit/IRP/Research_Project/Oxford-Flower-dataset/jpg, epochs=1, time=None, patience=100, batch=16, imgsz=224, save=True, save_period=1, cache=False, device=cpu, workers=8, project=None, name=train38, exist_ok=False, pretrained=True, optimizer=AdamW, verbose=True, seed=0, deterministic=True, single_cls=False, rect=False, cos_lr=True, close_mosaic=10, resume=False, amp=True, fraction=1.0, profile=False, freeze=None, multi_scale=False, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, vid_stride=1, stream_buffer=False, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, embed=None, show=False, save_frames=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, show_boxes=True, line_width=None, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=True, opset=None, workspace=4, nms=False, lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.01, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, bgr=0.0, mosaic=1.0, mixup=0.0, copy_paste=0.0, copy_paste_mode=flip, auto_augment=randaugment, erasing=0.4, crop_fraction=1.0, cfg=None, tracker=botsort.yaml, save_dir=C:\runs\classify\train38 train: C:\Users\derk_\Documents\Universiteit\IRP\Research_Project\Oxford-Flower-dataset\jpg\train... found 6149 images in 102 classes: ERROR ❌️ requires 2 classes, not 102 val: C:\Users\derk_\Documents\Universiteit\IRP\Research_Project\Oxford-Flower-dataset\jpg\val... found 1020 images in 102 classes: ERROR ❌️ requires 2 classes, not 102 test: C:\Users\derk_\Documents\Universiteit\IRP\Research_Project\Oxford-Flower-dataset\jpg\test... found 1020 images in 102 classes: ERROR ❌️ requires 2 classes, not 102 Overriding model.yaml nc=1000 with nc=2 from n params module arguments
0 -1 1 1392 ultralytics.nn.modules.conv.Conv [3, 48, 3, 2]
1 -1 1 41664 ultralytics.nn.modules.conv.Conv [48, 96, 3, 2]
2 -1 2 111360 ultralytics.nn.modules.block.C2f [96, 96, 2, True]
3 -1 1 166272 ultralytics.nn.modules.conv.Conv [96, 192, 3, 2]
4 -1 4 813312 ultralytics.nn.modules.block.C2f [192, 192, 4, True]
5 -1 1 664320 ultralytics.nn.modules.conv.Conv [192, 384, 3, 2]
6 -1 4 3248640 ultralytics.nn.modules.block.C2f [384, 384, 4, True]
7 -1 1 2655744 ultralytics.nn.modules.conv.Conv [384, 768, 3, 2]
8 -1 2 7084032 ultralytics.nn.modules.block.C2f [768, 768, 2, True]
9 -1 1 988162 ultralytics.nn.modules.head.Classify [768, 2]
YOLOv8m-cls summary: 141 layers, 15,774,898 parameters, 15,774,898 gradientsThe problem
The "[...] ERROR ❌️ requires 2 classes, not 102 [...]" is giving for all my data splits.
My yaml file.
The content of my yaml file:
names: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102] nc: 102 path: C:/Users/my_several_folders/Oxford-Flower-dataset/jpg test: test/images test_label_dir: test/labels train: train/images train_label_dir: train/labels val: val/images val_label_dir: val/labels
The length of names is equal to the value of nc, 102, so that is not disparate.
My folder structure
jpg/ ├── train/ │ ├── 1/ │ │ ├── img1.jpg │ │ └── img2.jpg │ ├── 2/ │ └── ... ├── val/ │ ├── 1/ │ ├── 2/ │ └── ... └── test/ ├── 1/ ├── 2/ └── ...
The names of the classes should thus correctly correspond to folder names of the folder wherein the images of that given class are stored.
Question
Are you familiar with the "[...] ERROR ❌️ requires 2 classes, not 102 [...]" error? What are the most common solutions to this problem?
Many thanks!
Glenn JocherUltralytics@D3RK0 it seems the model configuration is set to expect 2 classes instead of 102. Ensure that the
ncparameter in your model configuration matches the number of classes in your dataset. Adjust the model configuration tonc: 102to resolve this issue.D3RK0(đã chỉnh sửa)
@glenn-jocher Many thanks for your quick response!
How can I do that? I mean, as you can see from the content of my .yaml-file, the
ncparameter is already set to 102 andncis not an accepted hyperparameter in theYOLO()ormodel.train()function.
Glenn JocherUltralytics@D3RK0 ensure the model is correctly configured by setting
nc: 102in the model's YAML file before training. If the issue persists, verify that the model weights are compatible with the number of classes.xcf1
Hello, I'd like to ask you a question. In the evaluation results I generated, the scores.txt file shows AP: 0.429, AP_50: 0.702, AP_75: 0.457, AP_medium: 0.338, AP_large: 0.555, AR: 0.490, AR_50: 0.725, AR_75: 0.536, AR_medium: 0.385, AR_large: 0.632. However, in the stdout.txt file, 0.429 is the value for AP_0.50:0.95. So, I'm confused about where to find the official COCO AP and AR values. Below are screenshots of my two text files, the first being scores.txt and the second being stdout.txt.
Glenn JocherUltralytics(đã chỉnh sửa)The official COCO AP (Average Precision) metric is AP@0.50:0.95 which corresponds to the 0.429 value in your results. This matches both your scores.txt AP value and stdout.txt AP_0.50:0.95. For full details on COCO evaluation metrics, see the official COCO evaluation documentation.
-
rakezshre
Hi, I wanted to use MVTec dataset for training in Ultralytics framework with yolo. But the dataset doesnt have labelling but instead it has ground_truth with some parameters and masking. Is it possible to make a yaml file for the MVTec dataset (most easiest way)? If there is any method. Please let me know.
Thanks.
Glenn JocherUltralyticsTo use the MVTec dataset with YOLO, you'll need to convert the ground truth and masks into YOLO format. This involves creating bounding box annotations and a
data.yamlfile. You can refer to the Ultralytics documentation for guidance on dataset preparation and formatting. If you have further questions, feel free to ask!rakezshre
Is there any easyway to convert MVTec dataset with YOLO with ground truth and masks. It consists of large dataset and creating bounding box annotation seems time consuming. I can see the ultralytics format for data.yaml. But issue is with the bounding box consversion.
Glenn JocherUltralyticsTo convert the MVTec dataset for YOLO, you'll need to create bounding box annotations from the masks and ground truth. Tools like LabelImg can help with manual annotation. Once you have the annotations, you can format them into YOLO's required structure and create a
data.yamlfile. For more details, visit the Ultralytics documentation on dataset preparation.
Andriw75
I am usually interested in understanding what data I am adding to my dataset, as this can be beneficial or harmful depending on the project. I am trying to initialize the YOLO dataset to apply transformations required by the training parameters, but I often encounter errors. Thank you in advance for your help!
from ultralytics.data.dataset import YOLODataset, v8_transforms from ultralytics.engine.trainer import check_det_dataset
class Hyperparameters: def init(self, hyp_dict): for key, value in hyp_dict.items(): setattr(self, key, value)
Initialize the YOLO dataset
dataset = YOLODataset( img_path="path/to/images", # Replace with your image path data=check_det_dataset("path/to/dataset.yaml"), # Replace with your dataset configuration imgsz=640, batch_size=1 )
Define hyperparameters for transformations
hyp = { "mosaic": 1.0, "copy_paste": 0.5, "degrees": 10.0, "translate": 0.2, "scale": 0.9, "shear": 0.5, "perspective": 0.4, "copy_paste_mode": 'flip', 'mixup': 0.5, 'hsv_h': 0.1, 'hsv_s': 0.1, 'hsv_v': 0.1, 'flipud': 0.1, 'fliplr': 0.1 }
hyperparams = Hyperparameters(hyp)
Apply transformations to the dataset
transforms = v8_transforms(dataset, imgsz=640, hyp=hyperparams)
Attempt to augment data
augmented_data = transforms(dataset[0])
albumentations: Blur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01, num_output_channels=3, method='weighted_average'), CLAHE(p=0.01, clip_limit=(1, 4.0), tile_grid_size=(8, 8)) albumentations: Blur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01, num_output_channels=3, method='weighted_average'), CLAHE(p=0.01, clip_limit=(1, 4.0), tile_grid_size=(8, 8))
Error Encountered When I run the code, I encounter the following error: ValueError: could not broadcast input array from shape (0,640,640) into shape (364,640,640) the size always changes
Glenn JocherUltralytics@Andriw75 it seems like the error might be due to mismatched image sizes. Ensure all images in your dataset are correctly sized to 640x640 before applying transformations. If the issue persists, double-check your dataset paths and configuration. For further details, you can refer to the Ultralytics documentation on datasets.
MehrsaMashhadi
Hello. I hope you are doing well. I have paired RGB and thermal images, and I want to train yolov9 with 4 channel data. I want the model to read the first 3 channels from the RGB folder, and the thermal image from the thermal folder. all of the paired images have the same name, they are in different folders named ir, and vi. can you please help me how I should address this to the model?
Glenn JocherUltralytics@MehrsaMashhadi to train YOLOv9 with 4-channel data, you'll need to modify the data loading process to combine RGB and thermal images into a single input. You can create a custom dataset class that reads images from both folders and concatenates them into a 4-channel tensor. Ensure your model architecture supports 4-channel input. For more details, refer to the dataset customization section in the Ultralytics documentation.
toxanbi
I am absolute newbiew in machine learning coming from the world of low-level and system programming (drivers, firmware, electronics and so on). I have some questions.
-
Is my understanding correct that in machine learning there is a term 'model' which denotes an interconnect of neurons, i.e. the topogy of a neural network, a data structure describing how neurons are connected to each other, and, on the other hand, there is a 'weights' or 'weight file' which holds coefficients describing how signals (stymulus, activations) of a particular neuron influences on other neurons? If this is correct, which one of these two is represented by .pt-file? Or .pt file holds both of these? What is anatomy of .pt-files and where can I learn about it?
-
Let's assume that we are going to make a NN which can classify or detect three types of objects: cats, frogs and birds. What is optimal strategy of mastering a dataset to learn it: a) A given images must contain either one of these object (annotated by bounding box) b) A given image must contain multiple objects of the same type. c) It's better for every image to have all three instances of these kinds on it c-a) And it's better to not overlap. c-b) And, countrary, it's better to have overlapping to learn NN to handle such cases.
Should I feed NN with a pictures which doesn't have objects of interest at all or it is useless?
-
Now instead of having three categories (cats, frogs and birds) we are going to add yet another one which is "other live-forms". Is it a good practive to feed NN with tonns of images of completely different (visually) animals all tagged (annotated) as "other live-forms" or it's better to annotate each animal (other than cat, frog or bird) by setting a class corresponding to their real-world kind? Won't it confuse a NN if crocodiles and kangooros are all annotated as the object of same class? I presume that a process of learning/training is all about finding a features which uniquelly distinguish one class of objects from the others by finding proper weights/coefficients and if vast variety of totally different objects must be considered all having the same type, it may be impossible to find proper weights at all. Or it's not the case? If it is, seems that for that particular task one should use two different NNs: one to distinguisth alive objects for non-alive, and the second stage NN to detect cats/frogs/dogs (and if the second one doesn't detect either of these, but the first one detected a life-form, then it is considered "other life-form").
-
It's stated that default YOLO models which are available on this website are pretrained on COCO dataset. I saw a discussion on whether it's better to learn your NN from scratch or use a model pretrained on COCO. From my point of view traning a model (which was originally trained on COCO dataset) on your own dataset does only make sense if your custom dataset has exactly the same combinartion of 80 classes as COCO? And if you have less categories than COCO or more categories or even exactly 80 but of completely different types (e.g. you are learning NN to distinguish 80 kinds of vehicle motors), then the only option is learning from scratch?
-
I can't find a complete and strict definition of that the term 'val' or 'validation' means in context of training a model? Does it affects behaviour of the model or it is just a way to see how well training went?
-
When we learn a model to detect cats we feed it with images of what is DEFINITELY a cat. But is there a way to show it depiciting objects that are DEFINITELY NOT a cat to avoid false-positives? Other than introducing separate categories for objects that looks very similar to a cat and may be confused with cats but are not really a cat.
-
Many articles and videos tell us that YOLO format of labels is just s plain-text file with separate line for every label and each line consists of 5 fields; class-id and normalized coordinates of a bounding-box. But what about instance segmentation tasks? Oriented boundong box detection? Bone prediction (aka post)? Doesn't it require completely different and more complex format of annotations (compared to just specifying bounding box)?
Glenn JocherUltralytics@toxanbi 1. Your understanding is correct. The
.ptfile in PyTorch contains both the model architecture and the weights. You can learn more about the anatomy of.ptfiles in the PyTorch documentation.-
For optimal dataset creation, include diverse scenarios: single objects, multiple objects, overlapping objects, and images without objects. This helps the model generalize better.
-
It's better to have specific classes for different animals rather than a generic "other live-forms" class. This avoids confusion and improves model accuracy.
-
Pretraining on COCO is beneficial even if your dataset differs. Transfer learning can help the model learn faster and perform better, even with different categories.
-
Validation (val) is used to evaluate the model's performance on a separate dataset during training. It doesn't affect the model's behavior but helps monitor training progress.
-
To reduce false positives, you can include images without the target object in your training dataset. This helps the model learn what not to detect.
-
For tasks like instance segmentation, oriented bounding boxes, and pose estimation, the annotation format is more complex. Refer to the specific task documentation for details on the required annotation formats.
-
-
WARHE8D
Hello, how can i update my model and dataset to public? I only see 2 options private and anyone with link. thanks!
Paula DerrengerUltralytics@WARHE8D to make your model and dataset public, you need to ensure they are properly shared on a platform that supports public access. Currently, the options you mentioned ("private" and "anyone with link") are likely platform-specific settings. If you're using a service like Google Drive or Dropbox, you may need to adjust the sharing settings to "public" or "anyone with the link can view." For more detailed steps on contributing datasets to Ultralytics, please refer to the Contribute New Datasets section in our documentation.
1
1729asraful
I have 47 classes csv file. each file contains 100 images in csv formate with label. now how I can traine it?
Glenn JocherUltralytics(đã chỉnh sửa)@1729asraful hi there!
To train your model using a CSV file containing 47 classes and 100 images per class, you'll need to follow a few steps to prepare your data and then use the Ultralytics YOLO framework for training. Here’s a concise guide to get you started:
Step 1: Convert CSV to YOLO Format
First, you need to convert your CSV annotations into the YOLO format. Each image should have a corresponding
.txtfile with annotations in the format:<class> <x_center> <y_center> <width> <height>Where:
<class>is the class index (0 to 46 for your 47 classes).<x_center>,<y_center>,<width>, and<height>are normalized values (between 0 and 1) relative to the image dimensions.
Step 2: Organize Your Dataset
Organize your dataset into the following structure:
dataset/ ├── train/ │ ├── images/ │ └── labels/ └── val/ ├── images/ └── labels/Place your images in the
images/directories and the corresponding YOLO format annotation files in thelabels/directories.Step 3: Create a
data.yamlFileCreate a
data.yamlfile in the root of your dataset directory with the following content:train: path/to/dataset/train/images val: path/to/dataset/val/images nc: 47 # number of classes names: [class0, class1, ..., class46] # list of class namesStep 4: Train Your Model
You can now train your model using the Ultralytics YOLO framework. Here’s an example using the CLI:
yolo detect train data=path/to/data.yaml model=yolo26n.pt epochs=100 imgsz=640Or using Python:
from ultralytics import YOLO # Load a model model = YOLO('yolo26n.pt') # load a pretrained model # Train the model results = model.train(data='path/to/data.yaml', epochs=100, imgsz=640)Additional Resources
For more detailed information on dataset preparation and training, please refer to the Ultralytics Datasets Documentation.
If you encounter any issues, please provide a minimum reproducible example so we can assist you better. You can find more details on how to create one here.
Happy training! 🚀
1729asraful
Thanks a lot
Glenn JocherUltralytics(đã chỉnh sửa)@1729asraful you're welcome! 😊
To train your model using a CSV file containing 47 classes and 100 images per class, you'll need to convert your CSV annotations into the YOLO format and organize your dataset accordingly. Here’s a step-by-step guide:
Step 1: Convert CSV to YOLO Format
First, convert your CSV annotations into the YOLO format. Each image should have a corresponding
.txtfile with annotations in the format:<class> <x_center> <y_center> <width> <height>Where:
<class>is the class index (0 to 46 for your 47 classes).<x_center>,<y_center>,<width>, and<height>are normalized values (between 0 and 1) relative to the image dimensions.
Step 2: Organize Your Dataset
Organize your dataset into the following structure:
dataset/ ├── train/ │ ├── images/ │ └── labels/ └── val/ ├── images/ └── labels/Place your images in the
images/directories and the corresponding YOLO format annotation files in thelabels/directories.Step 3: Create a
data.yamlFileCreate a
data.yamlfile in the root of your dataset directory with the following content:train: path/to/dataset/train/images val: path/to/dataset/val/images nc: 47 # number of classes names: [class0, class1, ..., class46] # list of class namesStep 4: Train Your Model
You can now train your model using the Ultralytics YOLO framework. Here’s an example using the CLI:
yolo detect train data=path/to/data.yaml model=yolo26n.pt epochs=100 imgsz=640Or using Python:
from ultralytics import YOLO # Load a model model = YOLO('yolo26n.pt') # load a pretrained model # Train the model results = model.train(data='path/to/data.yaml', epochs=100, imgsz=640)For more detailed information on dataset preparation and training, please refer to the Ultralytics Datasets Documentation.
If you encounter any issues, please provide a minimum reproducible example so we can assist you better. You can find more details on how to create one here.
Happy training! 🚀
Llll0l0l
Hello, I'm new to machine learning, is it possible to train videos? i turned them into imgs however will it understand that the label belongs to continuous imgs that are sequential ?
Thank you for reading
Paula DerrengerUltralytics(đã chỉnh sửa)@Llll0l0l hello,
Welcome to the world of machine learning! 🌟 Yes, it is indeed possible to train models using video data. Converting videos into sequential images is a common practice. However, to ensure that the model understands the temporal context (i.e., that the images are sequential and belong to a continuous video), you might want to consider using multi-object tracking (MOT) techniques.
In multi-object tracking, the model not only detects objects in each frame but also assigns a unique ID to each detected object, maintaining this ID across frames. This way, the model can track the movement and changes of objects over time, understanding the sequential nature of the data.
Here’s a brief overview of how you can approach this:
- Convert Video to Frames: You’ve already done this step by converting your video into images.
- Annotate Frames: Ensure that your images are annotated correctly. Each frame should have annotations that indicate the presence and location of objects.
- Use a Multi-Object Tracking Model: Ultralytics supports various models and configurations for multi-object tracking. You can use models like YOLO26 with trackers such as BoT-SORT or ByteTrack.
Here’s a simple example of how you can set up multi-object tracking using YOLO26:
from ultralytics import YOLO # Load a model model = YOLO("yolo26n.pt") # Load an official model # Perform tracking on a video source results = model.track("path/to/your/video.mp4", show=True) # Tracking with default trackerFor more detailed guidance, you can refer to the Ultralytics documentation on multi-object tracking.
If you encounter any issues or need further assistance, please ensure you are using the latest version of the Ultralytics packages. Additionally, providing a minimum reproducible example can greatly help in diagnosing and resolving any problems. You can find more information on creating a reproducible example here.
Happy experimenting, and feel free to reach out if you have more questions! 😊
Llll0l0l
Thank you very much)
Paula DerrengerUltralytics(đã chỉnh sửa)Hello @Llll0l0l,
Thank you for your kind words! 😊
Regarding your question about training on video data: converting videos into sequential images is a great start. However, to ensure the model understands the temporal context, you might want to explore multi-object tracking (MOT) techniques. These techniques help the model maintain object identities across frames, effectively understanding the continuity in the sequence.
Here's a brief guide on how to proceed:
- Convert Video to Frames: As you've done, convert your video into individual frames.
- Annotate Frames: Ensure each frame is annotated correctly. This involves labeling objects in each frame.
- Use Multi-Object Tracking: Utilize models like YOLO26 with trackers such as BoT-SORT or ByteTrack to maintain object identities across frames.
Here’s an example of how you can set up multi-object tracking using YOLO26:
from ultralytics import YOLO # Load a model model = YOLO("yolo26n.pt") # Load an official model # Perform tracking on a video source results = model.track("path/to/your/video.mp4", show=True) # Tracking with default trackerFor more detailed guidance, you can refer to the Ultralytics documentation on multi-object tracking.
If you encounter any issues, please ensure you are using the latest version of the Ultralytics packages. Providing a minimum reproducible example can also greatly help in diagnosing and resolving any problems. You can find more information on creating a reproducible example here.
Feel free to reach out if you have more questions. Happy experimenting! 🚀