MindSpore报错:AttributeError: ‘Tensor‘ has no attribute ‘‘
1 报错描述
1.1 系统环境
Hardware Environment(Ascend/GPU/CPU): GPU
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): 4.19.36-vhulk1907.1.0.h619.eulerosv2r8.aarch64
– GCC/Compiler version (if compiled from source):
1.2 基本信息
1.2.1 脚本
训练脚本构建了一个简单的张量Tensor,并尝试去获取张量中的数据。脚本如下:
import numpy as np
from mindspore import Tensor
a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32"))
print(a.data)
1.2.2 报错
这里报错信息如下:
Traceback (most recent call last):
File "demo.py", line 4, in <module>
print(a.data)
AttributeError: 'Tensor' object has no attribute 'data'
2 原因分析
在MindSpore中,Tensor对象并无属性data。而在脚本中第4行代码发现了尝试通过调用Tensor张量的data属性,获取Tensor中的数据。
通过官方文档查询Tensor可以发现,并未在官方公布属性中,查找到Tensor的data属性。
其实,要想获取Tensor中的数据,可以直接打印该Tensor,也可以通过asnumpy属性转化为numpy进行输出,或者其他方法转换。
3 解决方法
基于上面已知的原因,很容易做出如下修改:
此时执行成功,输出如下:
[[10. 11. 12.]
[13. 14. 15.]]
4 总结
定位报错问题的步骤:
1、 找到报错的用户代码行: print(a.data);
2、 根据日志报错信息中的关键字,缩小分析问题的范围:AttributeError,该关键字表示属性错误;
3、需要重点关注变量属性的正确性。