RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 3 and 2 in dimension 1

It is because the image shapes are not the same in your datasets. For example, when process in batch, you cannot stack a [512, 512, 3] tensor and a [512, 317, 3] tensor together and feed them into a model. So, you have to do some tranformation to make them the same shape.

5 Likes

Thank you so much :sweat_smile: :sweat_smile: :sweat_smile: :sweat_smile:

Thanks, I had the same problem, This simple line of code solved my issue after struggling about 4 hours. :grinning:

I am encountering a similar problem. I am working on medical image segmentation on a dataset of nii images. I am getting the following error:
RuntimeError: Sizes of tensors must match except in dimension 1. Got 25 and 26 in dimension 2 (The offending index is 1)
PS: The size of images is (192,192,16) and I found this out by using the “first” function which returns the first element of the dataset. I want to find the size of all images in the dataset but I am confused totally as am a beginner. Also, is there a way to resize all the nii images to one size to be on the safer side as torch vision transforms dont work on nii files and monai transforms(which work on nii images) doesnt have any resize function. Please help me out.

I had the same issue. The training was working on one dataset but not working on a similar dataset and causing the same error. Just realized that some of the images in the dataset that caused the error had 4 channels instead of 3. Changing those images with 4 channels to 3 fixed the issue. Thanks for the help :slightly_smiling_face: :v:

Probably it got added late but Monai have resize function: Transforms — MONAI 1.3.0 Documentation