MindSpore报错 sth should be initialized as a Parameter type in ...

在MindSpore中,网络类的变量需要在__init__方法中使用Parameter进行初始化,不能直接在construct函数中赋值。错误信息表明self.val应被初始化为Parameter类型。解决方法是将self.val定义为Parameter,如`self.val=Parameter(Tensor(1.0,ms.float32),name=var)`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

系统环境

Hardware Environment(Ascend/GPU/CPU): ALL Software Environment: MindSpore version (source or binary): 1.6.0 & Earlier versions Python version (e.g., Python 3.7.5): 3.7.6 OS platform and distribution (e.g., Linux Ubuntu 16.04): Ubuntu GCC/Compiler version (if compiled from source): gcc 9.4.0

python代码样例

在网络中定义一个参数,并在训练过程中更新值,如下:

from mindspore import nn, Tensor, Parameter
import numpy as np

classNet(nn.Cell):def__init__(self):
        super(Net, self).__init__()
        self.val = 2.0defconstruct(self, x):
        self.val = x
        return0

net = Net()
output = net(1.0)
复制

执行代码发现报错。

报错信息

Traceback (most recent call last):
  File "test_var.py", line 15, in <module>
    output = net(1.0)
  File "C:\Users\46638\miniconda3\envs\mindspore\lib\site-packages\mindspore\nn\cell.py", line 477, in __call__
    out = self.compile_and_run(*args)
  File "C:\Users\46638\miniconda3\envs\mindspore\lib\site-packages\mindspore\nn\cell.py", line 803, in compile_and_run
    self.compile(*inputs)
  File "C:\Users\46638\miniconda3\envs\mindspore\lib\site-packages\mindspore\nn\cell.py", line 790, in compile
    _cell_graph_executor.compile(self, *inputs, phase=self.phase, auto_parallel_mode=self._auto_parallel_mode)
  File "C:\Users\46638\miniconda3\envs\mindspore\lib\site-packages\mindspore\common\api.py", line 632, in compile
    result = self._graph_executor.compile(obj, args_list, phase, self._use_vm_mode())
TypeError: mindspore\ccsrc\pipeline\jit\parse\parse.cc:1923 HandleAssignClassMember] 'self.val' should be initialized as a 'Parameter'typein the '__init__' function, but got '2.0' with type'float.

In file test_var.py(11)
        self.val = x
复制

原因分析

报错信息提示,变量self.val不支持在construct函数中直接赋值,需要使用Parameter进行初始化。此时可以查询mindspore官网中Parameter接口的使用说明。

在样例中发现,参数需要在__init__方法中初始化。

解决方法

from mindspore import nn, Tensor, Parameter
import mindspore as ms
import numpy as np

classNet(nn.Cell):def__init__(self):
        super(Net, self).__init__()
        self.val = Parameter(Tensor(1.0, ms.float32), name="var")

    defconstruct(self, x):
        self.val = x
        return0

net = Net()
output = net(Tensor(2.0, ms.float32))
复制

总结

Cell网络中的变量需要在__init__中进行定义,并且使用Parameter接口进行初始化。

参考文档

Parameter

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值