pytorch: grad can be implicitly created only for scalar outputs

这个错误很早就遇到过但是没看到网上叙述清楚的,这里顺便写一下。
这里贴一下autograd.grad()的注释

grad(outputs, inputs, grad_outputs=None, retain_graph=None, create_graph=False, only_inputs=True, allow_unused=False)
    Computes and returns the sum of gradients of outputs w.r.t. the inputs.
    ``grad_outputs`` should be a sequence of length matching ``output``
    containing the pre-computed gradients w.r.t. each of the outputs. If an
    output doesn't require_grad, then the gradient can be ``None``).
    If ``only_inputs`` is ``True``, the function will only return a list of gradients
    w.r.t the specified inputs. If it's ``False``, then gradient w.r.t. all remaining
    leaves will still be computed, and will be accumulated into their ``.grad``
    attribute.
    
    Arguments:
        outputs (sequence of Tensor): outputs of the differentiated function.
        inputs (sequence of Tensor): Inputs w.r.t. which the gradient will be
            returned (and not accumulated into ``.grad``).
        grad_outputs (sequence of Tensor): Gradients w.r.t. each output.
            None values can be specified for scalar Tensors or ones that don't require
            grad. If a None value would be acceptable for all grad_tensors, then this
            argument is optional. Default: None.
        retain_graph (bool, optional): If ``False``, the graph used to compute the grad
            will be freed. Note that in nearly all cases setting this option to ``True``
            is not needed and often can be worked around in a much more efficient
            way. Defaults to the value of ``create_graph``.
        create_graph (bool, optional): If ``True``, graph of the derivative will
            be constructed, allowing to compute higher order derivative products.
            Default: ``False``.
        allow_unused (bool, optional): If ``False``, specifying inputs that were not
            used when computing outputs (and therefore their grad is always zero)
            is an error. Defaults to ``False``.

如下代码

>>> a=Variable(torch.FloatTensor([1,2,3]),requires_grad=True)
>>> b=3*a    
>>> autograd.grad(outputs=b,inputs=a)  # 这里b为向量
RuntimeError: grad can be implicitly created only for scalar outputs

因为计算梯度时outputs需为标量(未指明grad_outputs或grad_outputs为None时),所以上面的代码会报错,而如下代码可以正常运行:

>>> a=Variable(torch.FloatTensor([1,2,3]),requires_grad=True)
>>> b=3*a
>>> z=b.sum()    
>>> autograd.grad(outputs=z,inputs=a) # 这里z为标量
(tensor([ 3.,  3.,  3.]),)

也可以通过指定grad_outputs,这时计算梯度就不再需要outputs为标量了,如下

>>> a=Variable(torch.FloatTensor([1,2,3]),requires_grad=True)
>>> b=3*a
>>> autograd.grad(outputs=b,inputs=a,grad_outputs=torch.ones_like(a))
(tensor([ 3.,  3.,  3.]),)

grad_outputs在GPU下时可写作以下形式

    grad_outputs = Variable(torch.Tensor(torch.ones_like(a)),requires_grad=False)
  • 15
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
在Python中,当使用自动微分库(如PyTorch)计算梯度时,只能为标量输出创建梯度。如果尝试为非标量输出创建梯度,就会出现"RuntimeError: grad can be implicitly created only for scalar outputs"的错误。这是因为在计算梯度时,需要将输出值与标量进行比较,以计算梯度的变化情况。 关于您提到的动手学深度学习中的MLP(多层感知机),我无法直接回答您的问题,因为您的问题中没有提到与此相关的具体内容。但是,根据您引用的内容,我可以看到您正在讨论梯度计算和使用PyTorch的情况。 为了使用MLP,您需要定义MLP的结构(包括层数、每层的神经元数量等),并且使用PyTorch的相关功能进行实现。然后,您可以通过向前传播输入,并通过损失函数计算损失。接下来,使用自动微分功能计算梯度,并使用优化算法(如随机梯度下降)更新模型的参数。这样,您就可以训练MLP模型并进行预测。 如果您有具体的问题或需要更详细的解释,请提供更多细节,以便我可以更好地帮助您。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [【深度学习】日常笔记7](https://blog.csdn.net/qq_45732909/article/details/131380169)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Python RuntimeError: thread.__init__() not called解决方法](https://download.csdn.net/download/weixin_38630358/12877726)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [RuntimeError: grad can be implicitly created only for scalar outputs的原因:Pytorch不支持对张量的...](https://blog.csdn.net/qq_40968179/article/details/127973793)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值