Output with shape [1, 28, 28] doesn't match the broadcast shape [3, 28, 28]

output with shape [1, 28, 28] doesn’t match the broadcast shape [3, 28, 28], this is the error how can I resolve this??

Based on the error message it looks like (some) images might be grayscale images and thus only contain one channel.
If that’s the case for all images, just use a single value for the mean and std arguments:

transforms.Normalize((0.5,), (0.5,))

Alternatively, if just a few images are gray while others are RGB images, you could convert these images after loading using:

img = Image.open(path).convert('RGB')
1 Like

I have the same problem, and I am converting the image to RGB as you suggest. Although really I want a grayscale image.

t_ = None
    if Hyper.is_grayscale:
        t_ = transforms.Compose([
            transforms.Grayscale(num_output_channels=1),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 5])
            ])
    else:
        t_ = transforms.Compose([
            transforms.ToTensor(),
             transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
            ])
    test_img1 = Image.open("test_examples/fast_train.jpg").convert("RGB")
    test_img1 =  t_(test_img1).unsqueeze(0)

If you want to keep the image tensors in the grayscale format, you could use the Normalize transformation from my previous post with a single mean and std value and it should work.
Currently you are passing 3 values for these stats, which will most likely yield a shape mismatch error.

Yes, I have since noticed that for Grayscale images I need only 1 value for the mean and 1 value for the std in the normalisation transformation, so I have fixed that now