RuntimeError: output with shape [1, 28, 28] doesn‘t match the broadcast shape [3, 28, 28]

RuntimeError: output with shape [1, 28, 28] doesn’t match the broadcast shape [3, 28, 28]

在用pytorch导入mnist数据时出现了上述错误:
RuntimeError: output with shape [1, 28, 28] doesn‘t match the broadcast shape [3, 28, 28]_第1张图片
报错程序:

transform = transforms.Compose([transforms.ToTensor(), 
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])])

报错原因:这是因为mnist图像都是灰度图像,只有一个通道,而上面的transforms.Normalize 却对三个通道都归一化了,这肯定会报错,所以只要像下面修改即可:

test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../date', train=False, 
    transform=transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.1307,), (0.3081,))
    ]))

0.1307和0.3081第一个是均值,第二个是标准差,这个对于不同的数据集来说是不同的,你需要根据样本来计算出他的均值和标准值,我这里为了简便,就大概的填了两个值。

还有第二种解决方案:
直接改成:

transform = transforms.Compose([transforms.ToTensor(), 
transforms.Normalize(mean=[0.5], std=[0.5])])

网上比较多的改成RGB通道的方式不可行,会造成后面优化参数时矩阵维度不匹配的问题
RuntimeError: output with shape [1, 28, 28] doesn‘t match the broadcast shape [3, 28, 28]_第2张图片
报这个错误:
RuntimeError: Given groups=1, weight of size 64 1 3 3, expected input[4, 3, 28, 28] to have 1 channels, but got 3 channels instead

你可能感兴趣的:(深度学习调试问题,深度学习,pytorch,pycharm)