【问题标题】:Error: The size of tensor a (892) must match the size of tensor b (400) at non-singleton dimension 3错误:张量 a (892) 的大小必须与非单维 3 的张量 b (400) 的大小相匹配
【发布时间】:2022-08-13 13:57:12
【问题描述】:

我正在使用pytorch在形状为(3,347,400)的图像数据集中构建自动编码器模型,当我尝试训练我的模型时遇到上述错误 这是我的编码器和解码器模型

class Autoencoder(nn.Module):
   def __init__(self):
       super().__init__()        
       self.encoder = nn.Sequential(
           nn.Conv2d(3, 16, 3, stride=2, padding=1),
           nn.ReLU(True),
           nn.Conv2d(16, 32, 3, stride=2, padding=1),
           nn.ReLU(True),
           nn.Conv2d(32, 64, 7) 
       )
       
      
       self.decoder = nn.Sequential(
           nn.ConvTranspose2d(64, 32, 7), 
           nn.ReLU(True),
           nn.ConvTranspose2d(32, 16, 3, stride=3,padding=1), 
           nn.ReLU(True),
           nn.ConvTranspose2d(16, 3, 3, stride=3,padding=1), 
           nn.Sigmoid()
       )

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

对于我使用 MSE() 的损失,有人可以帮我吗?

  • 你可以上传MSE代码吗?还有标签的形状。
  • 模型 = Autoencoder() 标准 = nn.MSELoss() 优化器 = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5) .. 这是我的损失,你能帮帮我吗给我定义自动编码器的结构?

标签: python pytorch conv-neural-network autoencoder


【解决方案1】:

制作自动编码器时要注意的一件事是输入形状和输出形状应该相同。

自动编码器由一个部分组成压缩输入信息(encoder) 和一部分将压缩信息转换为原始输入(decoder)。因此,输入的形状和输出的形状必须相同。

我稍微修改了您的自动编码器以匹配输入形状和输出形状。此代码将帮助您理解。

代码:

import torch
import torch.nn as nn

class Autoencoder(nn.Module):
   def __init__(self):
       super().__init__()        
       self.encoder = nn.Sequential(
           nn.Conv2d(3, 16, 3, stride=1, padding=1),
           nn.ReLU(True),
           nn.Conv2d(16, 32, 3, stride=1, padding=1),
           nn.ReLU(True),
           nn.Conv2d(32, 64, 7) 
       )
      
       self.decoder = nn.Sequential(
           nn.ConvTranspose2d(64, 32, 7), 
           nn.ReLU(True),
           nn.ConvTranspose2d(32, 16, 3, stride=1, padding=1), 
           nn.ReLU(True),
           nn.ConvTranspose2d(16, 3, 3, stride=1, padding=1), 
           nn.Sigmoid()
       )

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

model = Autoencoder()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)

x = torch.randn(3,347,400)
# When you modify the model, the output should be the same as the shape of x.
print(model(x).shape)

结果:

torch.Size([3, 347, 400])

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 2020-12-18
    • 2020-12-13
    • 1970-01-01
    • 2020-06-06
    • 2021-03-09
    • 2021-01-26
    • 2020-11-24
    • 2019-11-09
    相关资源
    最近更新 更多