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

PyTorch构建GAN时出现'NoneType' object is not callable错误求助

解决PyTorch生成器中'NoneType' object is not callable错误

你在构建GAN生成器时遇到的'NoneType' object is not callable错误,核心原因是**get_gen_block函数的缩进错误**,导致非final_block的场景下函数没有返回任何模块,最终self.block_1、self.block_2、self.block_3都为None,调用时自然会触发该错误。

问题代码中的错误点

你的get_gen_block函数里,第二个return语句被错误缩进在了if final_block == True:的代码块内,当final_block为False时,函数执行完if分支后没有任何返回,默认返回None:

def get_gen_block(in_channels, out_channels, kernel_size, stride, final_block = False):
  if final_block == True:
    return nn.Sequential(
        nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride),
        nn.Tanh()
    )

    return nn.Sequential(
        nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride),
        nn.BatchNorm2d(out_channels),
        nn.ReLU()
    )

修正后的代码

只需要把第二个return语句的缩进调整到和if同级即可:

def get_gen_block(in_channels, out_channels, kernel_size, stride, final_block = False):
  if final_block == True:
    return nn.Sequential(
        nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride),
        nn.Tanh()
    )

  return nn.Sequential(
      nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride),
      nn.BatchNorm2d(out_channels),
      nn.ReLU()
  )

验证修正效果

修正后,实例化Generator并测试前向传播:

import torch
import torch.nn as nn

# 实例化生成器
noise_dim = 100
gen = Generator(noise_dim)

# 生成测试噪声
test_noise = torch.randn(32, noise_dim)
output = gen(test_noise)
print(output.shape)  # 输出符合预期的张量形状,不再报错

内容的提问来源于stack exchange,提问作者Amit Pal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:40:26