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
相关产品推荐
相关产品推荐

