上述代码出现TypeError: ce_loss() got an unexpected keyword argument 'target'错误,请问如何改正
时间: 2023-07-30 20:10:22 浏览: 202
根据错误提示,`ce_loss()` 函数不支持 `target` 这个关键字参数,因此需要将代码中的 `target` 改成 `labels`。同时,需要将 `kappa` 作为标签传递给 `ce_loss()` 函数,而不是作为独立的参数传递。修改后的代码如下:
```
def adversarial(x, model, loss_func, c=1e-4, kappa=0, num_iter=100, lr=0.01):
"""Create adversarial examples using CW algorithm
Args:
- x: input image
- model: the neural network model
- loss_func: the loss function to use
- c: the weight for the L2 regularization term (default=1e-4)
- kappa: the confidence parameter (default=0)
- num_iter: number of iterations for the algorithm (default=100)
- lr: learning rate for the optimization (default=0.01)
Returns:
- x_adv: adversarial example
"""
x_adv = x.clone().detach().requires_grad_(True)
for i in range(num_iter):
output = model(x_adv)
loss = loss_func(output, kappa * torch.ones_like(output), labels=x, adversary=x_adv, c=c)
model.zero_grad()
loss.backward()
with torch.no_grad():
x_adv += lr * x_adv.grad
x_adv = torch.max(torch.min(x_adv, x + 0.35), x - 0.35)
x_adv = torch.clamp(x_adv, 0, 1)
x_adv.requires_grad_()
return x_adv.detach()
```
在调用 `loss_func()` 函数时,这里使用了 `kappa * torch.ones_like(output)` 将 `kappa` 扩展成与 `output` 相同的形状,作为标签传递给 `ce_loss()` 函数。
阅读全文