How to resolve runtime error due to size mismatch in PyTorch?

故事扮演 提交于 2020-02-26 20:49:09

问题


I am trying to implement a simple autoencoder using PyTorch. My dataset consists of 256 x 256 x 3 images. I have built a torch.utils.data.dataloader.DataLoader object which has the image stored as tensor. When I run the autoencoder, I get a runtime error:

size mismatch, m1: [76800 x 256], m2: [784 x 128] at /Users/soumith/minicondabuild3/conda-bld/pytorch_1518371252923/work/torch/lib/TH/generic/THTensorMath.c:1434

These are my hyperparameters:

batch_size=100,
learning_rate = 1e-3,
num_epochs = 100

Following is the architecture of my auto-encoder:

class autoencoder(nn.Module):
    def __init__(self):
        super(autoencoder, self).__init__()
        self.encoder = nn.Sequential(
            nn.Linear(3*256*256, 128),
            nn.ReLU(),
            nn.Linear(128, 64),
            nn.ReLU(True),
            nn.Linear(64, 12),
            nn.ReLU(True),
            nn.Linear(12, 3))

        self.decoder = nn.Sequential(
            nn.Linear(3, 12),
            nn.ReLU(True),
            nn.Linear(12, 64),
            nn.ReLU(True),
            nn.Linear(64, 128),
            nn.Linear(128, 3*256*256),
            nn.ReLU())

def forward(self, x):
    x = self.encoder(x)
    #x = self.decoder(x)
    return x

This is the code I used to run the model:

for epoch in range(num_epochs):
for data in dataloader:
    img = data['image']
    img = Variable(img)
    # ===================forward=====================
    output = model(img)
    loss = criterion(output, img)
    # ===================backward====================
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
# ===================log========================
print('epoch [{}/{}], loss:{:.4f}'
      .format(epoch+1, num_epochs, loss.data[0]))
if epoch % 10 == 0:
    pic = show_img(output.cpu().data)
    save_image(pic, './dc_img/image_{}.jpg'.format(epoch))

回答1:


If your input is 3 x 256 x 256, then you need to convert it to B x N to pass it through the linear layer: nn.Linear(3*256*256, 128) where B is the batch_size and N is the linear layer input size. If you are giving one image at a time, you can convert your input tensor of shape 3 x 256 x 256 to 1 x (3*256*256) as follows.

img = img.view(1, -1) # converts [3 x 256 x 256] to 1 x 196608
output = model(img)



回答2:


Whenever you have:

RuntimeError: size mismatch, m1: [a x b], m2: [c x d]

all you have to care is b=c and you are done:

m1 is [a x b] which is [batch size x in features]

m2 is [c x d] which is [in features x out features]



来源:https://stackoverflow.com/questions/49606482/how-to-resolve-runtime-error-due-to-size-mismatch-in-pytorch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!