python自定义损失函数_PyTorch中自定义损失函数的变量输入的AttributeError

本文介绍了如何在PyTorch中创建一个自定义损失函数,用于计算多输出多标签问题的交叉熵损失。在前向传播过程中,作者遇到`AttributeError`,因为目标变量不需要梯度。代码示例展示了如何实现这一功能,但遇到了问题,导致运行时错误。作者尝试找到解决方案,并希望实现类似BCELoss但支持多标签的类。
摘要由CSDN通过智能技术生成

我已经制作了一个自定义损失函数来计算多输出多标签问题的交叉熵(CE) . 在课堂上,我想设置我不需要渐变的目标变量 . 我在前向函数中使用类外部的预定义函数(取自pytorch源代码)来执行此操作 .

def _assert_no_grad(variable):

assert not variable.requires_grad

def forward(self, predicted, target):

"""

Computes cross entropy between targets and predictions.

"""

# No gradient over target

_assert_no_grad(target)

# Define variables

p = predicted.clamp(0.01, 0.99)

t = target.float()

#Compute cross entropy

h1 = p.log()*t

h2 = (1-t)*((1-p).log())

ce = torch.add(h1, h2)

ce_out = torch.mean(ce, 1)

ce_out = torch.mean(ce_out, 0)

# Save for backward step

self.save_for_backward(ce_out)

此时,当我在批量for循环中运行代码时(见下文),我收到以下错误:

AttributeError:'torch.FloatTensor'对象没有属性'requires_grad'

这看起来很简单,因为我们应该传递一个torch.autograd.Variable,但是我已经这样做了,如下面的片段中所示 .

for t in range(50):

print('Epoch {}'.format(t))

if t > 0:

print('Loss ->', loss)

for batch_idx, (x_batch, y_batch) in enumerate(train_loader):

# Wrap in Variable

x_in, target = Variable(x_batch), Variable(y_batch)

predicted = model(x_in)

# Compute and print loss

loss = criterion(predicted, target)

# Zero gradients, perform a backward pass, and update the weights.

optimizer.zero_grad()

loss.backward()

optimizer.step()

要添加注释,我的最终目标是生成一个类似BCELoss的类,除了多个标签而不仅仅是二进制 . 我觉得我已经浏览了整个PyTorch文档,主要是使用这个和一些论坛条目 . http://pytorch.org/docs/master/notes/extending.html

所以

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值