系统环境
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接口进行初始化。