Pangoraw / PaDiM

:dolphin: Re-implementation of PaDiM and code for the article "Weakly Supervised Detection of Marine Animals in High Resolution Aerial Images"
https://arxiv.org/abs/2011.08785
MIT License
27 stars 4 forks source link

RuntimeError: The size of tensor a (4096) must match the size of tensor b (1024) at non-singleton dimension 0 #11

Closed rishabh-akridata closed 4 months ago

rishabh-akridata commented 4 months ago

Hi @Pangoraw I am getting the below error when doing model.predict. Is there anything wrong I am doing?

padim = PaDiM(num_embeddings=100, device="cpu", backbone="resnet18") 
for images, targets in tqdm(train_dataloader, total=len(train_dataloader)):
    padim.train_one_batch(images)

results = []
targets = []
for batch_images, batch_targets in tqdm(test_dataloader, total=len(test_dataloader)):
  distances = padim.predict(batch_images)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[54], line 4
      2 targets = []
      3 for batch_images, batch_targets in tqdm(test_dataloader, total=len(test_dataloader)):
----> 4   distances = padim.predict(batch_images)
      5   # results.append(distances)
      6   # targets.append(batch_targets) 

File ~/sec_disk/padim/padim/padim.py:151, in PaDiM.predict(self, new_imgs, params, compare_all)
    149     distances, _ = distances.min(dim=0)
    150 else:
--> 151     distances = mahalanobis_sq(embeddings, means, inv_cvars)
    152 return torch.sqrt(distances)

File ~/sec_disk/padim/padim/utils/distance.py:35, in mahalanobis_sq(x, mu, sigma_inv)
     23 def mahalanobis_sq(x: Tensor, mu: Tensor, sigma_inv: Tensor) -> Tensor:
     24     """
     25     The squared mahalanobis distance using PyTorch
     26     Params
   (...)
     33         dist: Distance tensor of size (h * w, 1)
     34     """
---> 35     delta = x - mu  # (h * w, c)
     36     temp = torch.matmul(sigma_inv, delta.unsqueeze(-1))  # (h * w, c, 1)
     37     dist = torch.matmul(delta.unsqueeze(1), temp)  # (h * w, 1, 1)

RuntimeError: The size of tensor a (4096) must match the size of tensor b (1024) at non-singleton dimension 0

Thanks

Pangoraw commented 4 months ago

what is the size of images here ? one should set corresponding size argument to PaDiM constructor

rishabh-akridata commented 4 months ago

Okay, it's working now, thanks for the super quick response @Pangoraw. I am closing this issue.

rishabh-akridata commented 4 months ago

Passing size parameter solves this issue.