0
点赞
收藏
分享

微信扫一扫

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

三千筱夜 2022-04-19 阅读 112

系统环境

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

class Net(nn.Cell):
    def __init__(self):
        super(Net, self).__init__()
        self.val = 2.0

    def construct(self, x):
        self.val = x
        return 0

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' type in 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

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

    def construct(self, x):
        self.val = x
        return 0

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

总结

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

 

举报

相关推荐

0 条评论