Skip to content

Can --image-weights and DDP training be compatible by building image-weighted dataset? #13415

@Scorbinwen

Description

@Scorbinwen

Search before asking

Question

I have searched the YOLOv5 issues and discussions e.g.#3275 , the lastest official code seems still be incompatible for "--image-weights" and DDP training, but it's needed for my task when my dataset is highly class-unbalanced.
So I implement an image-weighted dataset by estimating repeat times for images:

def expand_indices(indices, image_weight):
    expanded_indices = []
    for idx, weight in zip(indices, image_weight):
        # count is repeat times
        count = int(weight)
        expanded_indices.extend([idx] * count)

    return expanded_indices

class LoadImagesAndLabelsAndMasks(LoadImagesAndLabels):  # for training/testing
    def __init__(
            self,
            path,
            img_size=640,
            batch_size=16,
            num_classes=None,
            augment=False,
            hyp=None,
            rect=False,
            cache_images=False,
            single_cls=False,
            stride=32,
            pad=0,
            prefix="",
            downsample_ratio=1,
            overlap=False,
            usegt=False,
            use_gray=False,
            gt_type='input-concat'
    ):
        super().__init__(path, img_size, batch_size, augment, hyp, rect, cache_images, single_cls,
                         stride, pad, prefix, usegt, gt_type)
        self.downsample_ratio = downsample_ratio
        self.overlap = overlap
        if num_classes is not None:
            self.num_classes = num_classes
            cw = labels_to_class_weights(self.labels, self.num_classes) * (1 - np.zeros(self.num_classes)) ** 2 # class weights
            iw = labels_to_image_weights(self.labels, nc=self.num_classes, class_weights=cw)  # image weights
            min_iw = torch.min(iw)
            iw = torch.round(iw / min_iw)
            repeat_tensor = lambda rep_list: expand_indices(rep_list, iw.int().tolist()) if rep_list is not None else None
            self.indices = repeat_tensor(self.indices)
            self.ims = repeat_tensor(self.ims)
            self.im_files = repeat_tensor(self.im_files)
            self.npy_files = repeat_tensor(self.npy_files)
            self.labels = repeat_tensor(self.labels)
            self.segments = repeat_tensor(self.segments)

I hope someone can help me double check the implementation, if it's ok, I will be grad to contribute to the Yolov5 community.

Additional

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    detectObject Detection issues, PR'senhancementNew feature or requestquestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions