ipython下运行代码出现 is a built-in class错误

这个问题是我在做模型剪枝的时候遇到的

  1. 先载入VGG16模型,更改全连接层,使输出单元个数与自己待处理的数据类别个数一致。
  2. 冻住卷积层,只训练全连接层。学习率设为0.0001,momentum=0.9。
  3. 当设定的epoch数目满足的时候,把模型保存,使用命令:
torch.save(model, "./cifar-10/5epochs_cifar10_vgg_model")

4 . 然后在ipython使用以下命令加载模型:

model = torch.load("/home/smiles/tsq/PyTorch/pytorch-pruning/cifar-10/5epochs_cifar10_vgg_model").cuda()

这个时候就出现错误:

<module '__main__' (built-in)> is a built-in class

关于这个问题:网上有很多人遇到。应该是一个Bug。
python社区有关于这个问题的讨论:https://bugs.python.org/issue12920
在cifar10_prune.py中写代码,显示出各层是否需要训练:

if __name__ == '__main__':
    args = get_args()

    if args.train:
        # model = ModifiedVGG16Model().cuda() # use GPU and finetune 
        model = torch.load("/home/smiles/tsq/PyTorch/pytorch-pruning/cifar-10/10epochs_cifar10_vgg_model").cuda()
        for param in model.features.parameters():
            print "features's requires_grad is: ", param.requires_grad
        for param in model.classifier.parameters():
            print "classifier's requires_grad is: ", param.requires_grad    
    elif args.prune:
        model = torch.load("./cifar-10/cifar10_vgg_model").cuda

然后在终端下输入命令:

python cifar10_prune.py --train --train_path ./cifar-10/ --test_path ./cifar-10/
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
features's requires_grad is:  False
classifier's requires_grad is:  True
classifier's requires_grad is:  True
classifier's requires_grad is:  True
classifier's requires_grad is:  True
classifier's requires_grad is:  True
classifier's requires_grad is:  True

这说明,使用torch.save命令保存模型,除了把各层的参数保存了之外,还保存了各层参数是否需要进行训练这一设置,即requires_grad,当然还保存了其他,比如说网络结构,总之模型所有东西都保存了。

你可能感兴趣的:(Pytorch学习,模型剪枝)