pytorch 预期输入批次大小(56180)与目标批次大小(100)匹配

hrirmatl  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(168)

我得到以下错误。
ValueError:预期输入batch_size(56180)与目标batch_size(100)匹配。
我的模型的输入是3通道(RGB)227x227图像和批量大小是100。

torch.Size([100, 3, 227, 227])
torch.Size([100, 10, 111, 111])
torch.Size([100, 20, 53, 53])
torch.Size([56180, 100])
torch.Size([56180, 64])
torch.Size([56180, 64])
torch.Size([56180, 32])
torch.Size([56180, 32])
torch.Size([56180, 1])

这是二进制分类(真,假),所以我使最终输出为1

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()

        #input image 227x227x3

        self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
        self.conv2_drop = nn.Dropout2d()

        self.fc1 = nn.Linear(100, 64)
        self.fc3 = nn.Linear(64, 32)
        self.fc6 = nn.Linear(32, 1)

    def forward(self, x):
        print(x.shape)
        x = F.relu(F.max_pool2d(self.conv1(x), 2))
        print(x.shape)
        x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
        print(x.shape)
        x = x.view(-1, x.size(0))
        print(x.shape)
        x = F.relu(self.fc1(x))
        print(x.shape)
        x = F.dropout(x, training=self.training)
        print(x.shape)
        x = self.fc3(x)
        print(x.shape)
        x = F.dropout(x, training=self.training)
        print(x.shape)
        x = self.fc6(x)
        print(x.shape)
        return x

def train(model, train_loader, optimizer):
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(DEVICE), target.to(DEVICE)
        optimizer.zero_grad()
        output = model(data)
        target = target.unsqueeze(-1)
        loss = F.cross_entropy(output, target)

        loss.backward()
        optimizer.step()

我的问题是,我有100批图像,所以目标(Y)是100单位。但为什么我得到56180单位的结果?

xkrw2x1b

xkrw2x1b1#

更改视图功能(在正向方法中):

x = x.view(x.size(0), -1)

批量大小必须在0维中。
您的forward方法应该像这样定义:

def forward(self, x):
    x = F.relu(F.max_pool2d(self.conv1(x), 2))
    x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
    x = x.view(x.size(0), -1)
    x = F.relu(self.fc1(x))
    x = F.dropout(x, training=self.training)
    x = self.fc3(x)
    x = F.dropout(x, training=self.training)
    x = self.fc6(x)
    return x

相关问题