我的数据库具有大小为128 * 128 * 1的灰度图像,每个图像的批处理大小为10
我正在使用cnn模型,但在BatchNorm2d中遇到此错误
预期的4D输入(获得2D输入)
我发布了用于转换图像(灰度-张量-归一化)并将其分成批处理的方式
data_transforms = {
'train': transforms.Compose([
transforms.Grayscale(num_output_channels=1),
transforms.Resize(128),
transforms.CenterCrop(128),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])
]),
'val': transforms.Compose([
transforms.Grayscale(num_output_channels=1),
transforms.Resize(128),
transforms.CenterCrop(128),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5])
]),
}
data_dir = '/content/drive/My Drive/Colab Notebooks/pytorch'
dsets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ['train', 'val']}
dset_loaders = {x: torch.utils.data.DataLoader(dsets[x], batch_size=10,
shuffle=True, num_workers=25)
for x in ['train', 'val']}
dset_sizes = {x: len(dsets[x]) for x in ['train', 'val']}
dset_classes = dsets['train'].classes
我用了这个模型
class HeartNet(nn.Module):
def __init__(self, num_classes=7):
super(HeartNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=3, stride=1, padding=1),
nn.ELU(inplace=True),
nn.BatchNorm2d(64),
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
nn.ELU(inplace=True),
nn.BatchNorm2d(64),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
nn.ELU(inplace=True),
nn.BatchNorm2d(128),
nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1),
nn.ELU(inplace=True),
nn.BatchNorm2d(128),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
nn.ELU(inplace=True),
nn.BatchNorm2d(256),
nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1),
nn.ELU(inplace=True),
nn.BatchNorm2d(256),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.classifier = nn.Sequential(
nn.Dropout(0.5),
nn.Linear(16*16*256, 2048),
nn.ELU(inplace=True),
nn.BatchNorm2d(2048),
nn.Linear(2048, num_classes)
)
nn.init.xavier_uniform_(self.classifier[1].weight)
nn.init.xavier_uniform_(self.classifier[4].weight)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), 16 * 16 * 256)
x = self.classifier(x)
return x
我该如何解决这个问题?
答案 0 :(得分:1)
self.classifier
子网内的批处理规范层存在问题:self.features
子网完全卷积且需要BatchNorm2d
时,self.classifier
子网是完全连接的多层感知器(MLP)网络,本质上是一维的。请注意,在将forward
函数提供给分类器之前,该函数如何从特征图x
中删除空间尺寸。
尝试将BatchNorm2d
中的self.classifier
替换为BatchNorm1d
。