Knowledge Drilling
Knowledge Drilling

Reputation: 1036

Expected input batch_size (56180) to match target batch_size (100)

i am getting following error.

ValueError: Expected input batch_size (56180) to match target batch_size (100).

My model's input is 3 channel(RGB) 227x227 images And batch size is 100. And following is summary.

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])

This is binary classification(True, False), so i make final output is 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()

My question is that i have 100 batch images so that target(Y) is 100 units. But Why i am getting 56180 unit result?

Upvotes: 0

Views: 153

Answers (1)

core_not_dumped
core_not_dumped

Reputation: 867

Change the view function (in forward method):

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

The batch size must be in the 0 dimension.

Your forward method should be defined like this:

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

Upvotes: 1

Related Questions