MindSpore报类型错误TypeError: For 'Tensor', the type of `input_data` should be one of '['Tensor', 'ndarray',]'

1 报错描述

1.1 系统环境

Hardware Environment(Ascend/GPU/CPU): Ascend Software Environment: -- MindSpore version (source or binary): 1.6.0 -- Python version (e.g., Python 3.7.5): 3.7.6 -- OS platform and distribution (e.g., Linux Ubuntu 16.04): Ubuntu 4.15.0-74-generic -- GCC/Compiler version (if compiled from source):

1.2 基本信息

1.2.1 脚本

训练脚本如下:

from mindspore import Tensor
a = Tensor({1.1: -2.1})
output = a.abs()
print('result:',output)

1.2.2 报错

这里报错信息如下:

Traceback (most recent call last):
 File "demo.py", line 02, in <module>
a = Tensor({1.1: -2.1})
… 
TypeError: For 'Tensor', the type of `input_data` should be one of '['Tensor', 'ndarray', 'str_', 'list', 'tuple', 'float', 'int', 'bool', 'complex']', but got '{1.1: -2.1}' with type 'dict'.

原因分析

​ 对于MindSpore 1.6版本,通过官方api接口,构建简单单算子用例。在报错信息中,写到TypeError: For ‘Tensor’, the type of input_data should be one of ‘[‘Tensor’, ‘ndarray’, ‘str’, ‘list’, ‘tuple’, ‘float’, ‘int’, ‘bool’, ‘complex’]’, but got ‘{1.1: -2.1}’ with type ‘dict’,首先报错类型是TypeError,即类型错误,在随后的描述中写到,传入的input_data类型应该是’[‘Tensor’, ‘ndarray’, ‘str_’, ‘list’, ‘tuple’, ‘float’, ‘int’, ‘bool’, ‘complex’]中的一种,但是传入的却是字典类型。这点在官网对Tensor的介绍中也做了相应的描述。

​ 因此需要对传入的数据类型进行修改。

2 解决方法

基于上面已知的原因,很容易做出如下修改:

from mindspore import Tensor  
a = Tensor({1.1, -2.1})  
output = a.abs()  
print('result:',output)

此时执行成功,输出如下:

result: [1.1 2.1]

3 总结

定位报错问题的步骤:

1、找到报错的用户代码行: a = Tensor({1.1: -2.1}) ;

2、 根据日志报错信息中的关键字,缩小分析问题的范围: the type of input_data should be one of xxx, but got type ‘dict’ ;

3、需要重点关注变量定义、初始化的正确性。

4 参考文档

4.1 Tensor算子API接口