You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用nn.Sequential实现Autoencoder触发TypeError,寻求修复方案

问题排查与修复:Autoencoder实现中的TypeError错误

问题背景

使用PyTorch的nn.Sequential实现Autoencoder时触发TypeError,提示__init__() missing 2 required positional arguments: 'in_features' and 'out_features'。尝试修改卷积层参数写法、移除部分层后问题仍未解决。

错误根源分析

  1. 核心错误:无参数的Linear层
    错误栈看似指向Encoder初始化,但实际问题出在Decoder的nn.Sequential中:代码里写了nn.Linear()却没有传入任何参数,而nn.Linear必须指定in_features和out_features两个必填参数,这是触发报错的直接原因。且这个Linear层在卷积转置层之间完全多余,应直接删除。

  2. 次要错误:卷积层参数名误用
    nn.Conv2d和nn.ConvTranspose2d的输入输出通道参数名是in_channels和out_channels,而非代码中写的in_features和out_features(这是nn.Linear的参数名),虽PyTorch可识别位置参数,但写错参数名易引发混淆。

  3. 输出尺寸不匹配问题
    原Decoder中的ConvTranspose2d未设置output_padding,导致输出尺寸无法还原为输入的28x28,需添加output_padding=1修正尺寸。

修复后的完整代码

import torch
import torch.nn as nn

latent_dims = 4

class Encoder(nn.Module):
    def __init__(self):
        super().__init__()
        # input Nx1x28x28
        self.encoder = nn.Sequential(
             nn.Conv2d(in_channels=1, out_channels=16, kernel_size=(3,3), stride=2, padding=1), # out=16x14X14
             nn.ReLU(),
             nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3,3), stride=2, padding=1), # out 32x7x7
             nn.ReLU(),
             nn.Flatten(),
             nn.Linear(in_features=32*7*7, out_features=latent_dims)
        )

    def forward(self, x):
        return self.encoder(x)

class Decoder(nn.Module):
    def __init__(self):
        super().__init__()
        self.decoder= nn.Sequential(
            nn.Linear(in_features=latent_dims, out_features=32*7*7),
            nn.Unflatten(dim=1, unflatten_size=(32, 7, 7)),
            nn.ConvTranspose2d(in_channels=32, out_channels=16, kernel_size=3, stride=2, padding=1, output_padding=1), # out=16x14x14
            nn.ReLU(),
            nn.ConvTranspose2d(in_channels=16, out_channels=1, kernel_size=3, stride=2, padding=1, output_padding=1), # out=1x28x28
            nn.Sigmoid()
        )

    def forward(self, x):
        return self.decoder(x)

class Autoencoder(nn.Module):
    def __init__(self):
        super(Autoencoder, self).__init__()
        self.encoder = Encoder()
        self.decoder = Decoder()

    def forward(self, x):
        latent = self.encoder(x)
        recon = self.decoder(latent)
        return recon
    
# 测试初始化与尺寸匹配
autoencoder = Autoencoder()
test_input = torch.randn(1, 1, 28, 28)
output = autoencoder(test_input)
print(f"输入尺寸: {test_input.shape}, 输出尺寸: {output.shape}")

修复说明

  • 删除Decoder中多余的nn.Linear()层,解决参数缺失报错。
  • 将Conv2d和ConvTranspose2d的参数名修正为in_channels/out_channels,符合PyTorch API规范。
  • 为两个ConvTranspose2d添加output_padding=1,确保输出尺寸还原为28x28,与输入尺寸一致。
  • 在第一个ConvTranspose2d后添加nn.ReLU()激活层,保证模型的非线性表达能力。

内容的提问来源于stack exchange,提问作者Antony Prinz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 13:31:00