栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

系统环境

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 
    output = net(1.0)
  File "C:Users46638miniconda3envsmindsporelibsite-packagesmindsporenncell.py", line 477, in __call__
    out = self.compile_and_run(*args)
  File "C:Users46638miniconda3envsmindsporelibsite-packagesmindsporenncell.py", line 803, in compile_and_run
    self.compile(*inputs)
  File "C:Users46638miniconda3envsmindsporelibsite-packagesmindsporenncell.py", line 790, in compile
    _cell_graph_executor.compile(self, *inputs, phase=self.phase, auto_parallel_mode=self._auto_parallel_mode)
  File "C:Users46638miniconda3envsmindsporelibsite-packagesmindsporecommonapi.py", line 632, in compile
    result = self._graph_executor.compile(obj, args_list, phase, self._use_vm_mode())
TypeError: mindsporeccsrcpipelinejitparseparse.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接口进行初始化。

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/822715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号