how to use collate_fn properly in the code below?

Viewed 1861

My code is:

model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
dataset = PennFudanDataset('PennFudanPed', get_transform(train=True))
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=2, shuffle=True, num_workers=4,
collate_fn=utils.collate_fn)
# For Training
images,targets = next(iter(data_loader))
images = list(image for image in images)
targets = [{k: v for k, v in t.items()} for t in targets]
output = model(images,targets)   # Returns losses and detections
# For inference
model.eval()
x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
predictions = model(x)           # Returns predictions

I get the error:

"collate_fn=utils.collate_fn" shows error"name 'utils' is not defined". "module 'torch.utils' has no attribute 'collate_fn' error after adding torch.

1 Answers

Ok so I read the tutorial and it seems that it wants you to use the helper files in this repository: https://github.com/pytorch/vision/tree/master/references/detection .

In there is the utils.py which contains the collate_fn function. So it seems that you dont have downloaded/copied this repository to integrate it into your project, right?

To solve just that error, you could just copy the collate_fn in utils.py

def collate_fn(batch):
    return tuple(zip(*batch))

and paste it into your project. But since this tutorial probably wants you to use other util functions of utils.py too, you might want to download this directory and put it into your project directory so you can access it.

Related