FlowNet3D模型初始化时出现TypeError的原因及解决方法
FlowNet3D模型初始化TypeError问题解决
报错信息
Namespace(batch_size=64, cycle=False, dataset='SceneflowDataset', dataset_path='data/data_processed_maxcut_35_20k_2k_8192/', dropout=0.5, emb_dims=512, epochs=250, eval=False, exp_name='flownet3d', gaussian_noise=False, lr=0.001, model='flownet', model_path='', momentum=0.9, no_cuda=False, num_points=2048, seed=1234, test_batch_size=32, unseen=False, use_sgd=False) train : 20006 test : 2007 Traceback (most recent call last): File "main.py", line 282, in <module> main() File "main.py", line 254, in main net = FlowNet3D(args).cuda() File "/home/ubuntu/project/flownet3d_pytorch/model.py", line 13, in __init__ self.sa1 = PointNetSetAbstraction(npoint=1024, radius=0.5, nsample=16, in_channel=3, mlp=[32,32,64], group_all=False) File "/home/ubuntu/project/flownet3d_pytorch/util.py", line 225, in __init__ for out_channel in mlp2: TypeError: 'NoneType' object is not iterable
问题原因
PointNetSetAbstraction类的__init__方法中,mlp2参数默认值设为None,但代码直接对mlp2执行遍历操作。当实例化该类(如sa1至sa4)时未传入mlp2参数,就会触发None不可迭代的错误。
解决方案
方案一:修改默认参数为空列表
将mlp2的默认值从None改为空列表,这样即使不传入该参数,遍历操作也能正常执行:
class PointNetSetAbstraction(nn.Module): def __init__(self, npoint, radius, nsample, in_channel, mlp, mlp2 = [], group_all = False): super(PointNetSetAbstraction, self).__init__() self.npoint = npoint self.radius = radius self.nsample = nsample self.group_all = group_all self.mlp_convs = nn.ModuleList() self.mlp_bns = nn.ModuleList() self.mlp2_convs = nn.ModuleList() last_channel = in_channel+3 for out_channel in mlp: self.mlp_convs.append(nn.Conv2d(last_channel, out_channel, 1, bias = False)) self.mlp_bns.append(nn.BatchNorm2d(out_channel)) last_channel = out_channel for out_channel in mlp2: self.mlp2_convs.append(nn.Sequential(nn.Conv1d(last_channel, out_channel, 1, bias=False), nn.BatchNorm1d(out_channel))) last_channel = out_channel # 后续代码不变
方案二:增加非空判断
在遍历mlp2前添加判断,仅当mlp2不为None时执行循环:
class PointNetSetAbstraction(nn.Module): def __init__(self, npoint, radius, nsample, in_channel, mlp, mlp2 = None, group_all = False): super(PointNetSetAbstraction, self).__init__() self.npoint = npoint self.radius = radius self.nsample = nsample self.group_all = group_all self.mlp_convs = nn.ModuleList() self.mlp_bns = nn.ModuleList() self.mlp2_convs = nn.ModuleList() last_channel = in_channel+3 for out_channel in mlp: self.mlp_convs.append(nn.Conv2d(last_channel, out_channel, 1, bias = False)) self.mlp_bns.append(nn.BatchNorm2d(out_channel)) last_channel = out_channel # 修改此处,增加非空判断 if mlp2 is not None: for out_channel in mlp2: self.mlp2_convs.append(nn.Sequential(nn.Conv1d(last_channel, out_channel, 1, bias=False), nn.BatchNorm1d(out_channel))) last_channel = out_channel # 后续代码不变
两种方案均可解决问题:方案一操作简单,适配原项目多数场景;方案二更严谨,能避免意外传入None的情况。
内容的提问来源于stack exchange,提问作者kaka2u_
相关产品推荐
相关产品推荐

