1.系统环境
硬件环境(Ascend/GPU/CPU): GPU
软件环境:
– MindSpore 版本: 1.7.0
执行模式: 静态图(GRAPH) – Python 版本: 3.7.6
– 操作系统平台: linux
2.报错信息
2.1 问题描述
将需要优化的参数放入优化器中,直接将Tensor类型的参数放入,由于优化器需要的数据类型是Iterable,导致执行报错。
2.2 报错信息
TypeError: For 'Optimizer', the argument parameters must be Iterable type, but got .
2.3 脚本代码
class Attack(object):
def __init__(self,input_img,target_img,seed=None): if (seed != None): np.random.seed(seed) self.MEAN = Tensor([0.485, 0.456, 0.406]) self.STD = Tensor([0.229, 0.224, 0.225]) self.LOSS = Tensor(0) self.expand_dims = mindspore.ops.ExpandDims() self.imageize = ToPILImage() self.tensorize = ToTensor() self.normalize = P.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.resnet = get_net() self.input_tensor = Tensor(self.normalize(self.tensorize(input_img))) self.target_tensor = Tensor(self.normalize(self.tensorize(target_img))) mp.imsave('./outputs/input图像.jpg', np.transpose(self._reverse_norm(self.input_tensor).asnumpy(), (1, 2, 0))) mp.imsave('./outputs/target图像.jpg', np.transpose(self._reverse_norm(self.target_tensor).asnumpy(), (1, 2, 0))) self.input_emb = self.resnet(self.expand_dims(self.input_tensor,0)) self.target_emb = self.resnet(self.expand_dims(self.target_tensor,0)) self.adversarial_emb = None self.mask_tensor = self._create_mask(input_img) self.ref = self.mask_tensor self.opt = nn.Adam(self.mask_tensor, learning_rate=0.01, weight_decay=0.0001)
复制
复制
3.根因分析
看报错信息,翻译意思是实参参数必须是Iterable类型,即是可迭代的。
调试发现self.mask_tensor是Tensor类型,不能进行迭代。
通过查看文档,可以通过Parameter()更好的对训练参数进行设置。同时Python里有大量内置的iterable类型,如: list,str,tuple,dict等,可以将参数包装成list实现可迭代化。
4.解决方案
解决方案说明:把self.mask_tensor改成list类型:[Parameter(self.mask_tensor)],来实现可迭代化。
修改后代码:
class Attack(object):
def __init__(self,input_img,target_img,seed=None):
if (seed != None): np.random.seed(seed)
self.MEAN = Tensor([0.485, 0.456, 0.406])
self.STD = Tensor([0.229, 0.224, 0.225])
self.LOSS = Tensor(0)
self.expand_dims = mindspore.ops.ExpandDims()
self.imageize = ToPILImage()
self.tensorize = ToTensor()
self.normalize = P.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.resnet = get_net()
self.input_tensor = Tensor(self.normalize(self.tensorize(input_img)))
self.target_tensor = Tensor(self.normalize(self.tensorize(target_img)))
mp.imsave('./outputs/input图像.jpg', np.transpose(self._reverse_norm(self.input_tensor).asnumpy(), (1, 2, 0)))
mp.imsave('./outputs/target图像.jpg', np.transpose(self._reverse_norm(self.target_tensor).asnumpy(), (1, 2, 0)))
self.input_emb = self.resnet(self.expand_dims(self.input_tensor,0))
self.target_emb = self.resnet(self.expand_dims(self.target_tensor,0))
self.adversarial_emb = None
self.mask_tensor = self._create_mask(input_img)
self.ref = self.mask_tensor
self.opt = nn.Adam([Parameter(self.mask_tensor)], learning_rate=0.01, weight_decay=0.0001)
修改后程序正常运行。