加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何解决由于PyTorch中的大小不匹配导致的运行时错误

发布时间:2020-12-20 11:03:29 所属栏目:Python 来源:网络整理
导读:我正在尝试使用PyTorch实现一个简单的自动编码器.我的数据集由256 x 256 x 3图像组成.我已经构建了一个torch.utils.data.dataloader.DataLoader对象,该对象将图像存储为张量.当我运行autoencoder时,我收到运行时错误: size mismatch,m1: [76800 x 256],m2:
我正在尝试使用PyTorch实现一个简单的自动编码器.我的数据集由256 x 256 x 3图像组成.我已经构建了一个torch.utils.data.dataloader.DataLoader对象,该对象将图像存储为张量.当我运行autoencoder时,我收到运行时错误:

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

这些是我的超参数:

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

以下是我的自动编码器的架构:

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.Linear(12,3))

        self.decoder = nn.Sequential(
            nn.Linear(3,3*256*256),nn.ReLU())

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

这是我用来运行模型的代码:

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

解决方法

如果您的输入是3 x 256 x 256,那么您需要将其转换为B x N以将其传递通过线性层:nn.Linear(3 * 256 * 256,128)其中B是batch_size,N是线性图层输入大小.
如果您一次给出一个图像,可以将输入张量3 x 256 x 256转换为1 x(3 * 256 * 256),如下所示.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读