construct方法名称错误引起损失函数执行报错:The ‘sub‘ operation does not support the type [Tensor[Float32], None].

1 系统环境

硬件环境(Ascend/GPU/CPU): CPU

软件环境:

– MindSpore 版本: 1.8.0

  • 执行模式: 静态图(GRAPH)

– Python 版本: 3.7.6

– 操作系统平台: Windows

2 报错信息

2.1 问题描述

在自定义Cell网络中,construct函数名称错误定义了新的函数,导致基类Cell的construct没有实现引起报错。

2.2 报错信息

RuntimeError:The 'sub' operation does not support the type [Tensor[Float32], None].

2.3 脚本代码

from mindspore import nn, Tensor
import numpy as np
import mindspore
class Net(nn.Cell):
    def constuct(self, x):
        return x

def main():
    x = Tensor(np.array([1, 2, 3]), mindspore.float32)
    net = Net()
    y = net(x)
    loss = nn.MSELoss()
    out = loss(x, y)
    print("out=", out)复制

3 根因分析

看报错信息,WARNING Net没有重载'construct'方法。 代码里面写成了constuct

最终报错是sub不支持[Tensor[Float32], kMetaTypeNone]

如果Net没有重载'construct'方法,调用了父类的'construct'方法

父类的实现

也就是Net的返回值永远是None,然后将None传入到nn.MSELoss()中

313行 MSELoss会把两个入参相减,然后取平方。

两个参数一个是Tensor另一个是None,所以报sub操作类型不支持。

此时,切换到PYNATIVE_MODE跑下看看

PYNATIVE_MODE下整个流程更加清晰明了。

4 解决方案

解决方案说明:把constuct修改成construct

修改后代码:

from mindspore import nn, Tensor
import numpy as np
import mindspore
class Net(nn.Cell):
    def construct(self, x):
        return x

def main():
    x = Tensor(np.array([1, 2, 3]), mindspore.float32)
    net = Net()
    y = net(x)
    loss = nn.MSELoss()
    out = loss(x, y)
    print("out=", out)复制

正常执行结果out= 0.0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值