1 系统环境
硬件环境(Ascend/GPU/CPU): GPU
MindSpore版本: 不限版本
执行模式(PyNative/ Graph): PyNative
Python版本: 3.7.3
操作系统平台:不限
2 报错信息
2.1 问题描述
直接将Tensor从布尔值转换为浮点数,导致错误的结果。在类型转换前更改为numpy后,结果正确。
2.2 报错信息
想要得到的结果:
data = ms.Tensor(np.array([[0,0,0,0,0,0],[1,1,1,1,1,1],[1,1,1,1,1,1]]),ms.bool_)
print("data: \n",data)
print("inversed data: \n",~data)
new_data = ms.Tensor(~data.asnumpy(),ms.float32)
print("inversed data in float32:\n",new_data)
result = ops.ReduceSum()(new_data,0)
print("result: \n",result)
data:
[[False False False False False False]
[ True True True True True True]
[ True True True True True True]]
inversed data:
[[ True True True True True True]
[False False False False False False]
[False False False False False False]]
inversed data in float32:
[[1. 1. 1. 1. 1. 1.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
result:
[1. 1. 1. 1. 1. 1.]
实际得到的结果:
data = ms.Tensor(np.array([[0,0,0,0,0,0],[1,1,1,1,1,1],[1,1,1,1,1,1]]),ms.bool_)
print("data: \n",data)
print("inversed data: \n",~data)
new_data = ms.Tensor(~data.asnumpy(),ms.float32)
print("inversed data in float32:\n",new_data)
result = ops.ReduceSum()(new_data,0)
print("result: \n",result)
data:
[[False False False False False False]
[ True True True True True True]
[ True True True True True True]]
inversed data:
[[ True True True True True True]
[False False False False False False]
[False False False False False False]]
inversed data in float32:
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
result:
[2.3694278e-38 3.6013371e-43 0.0000000e+00 0.0000000e+00 1.0000000e+01 7.0000000e+00]
2.3 脚本代码
import mindspore as ms
data = ms.Tensor(np.array([[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]), ms.bool_)
print(data)
print(~data)
new_data = ms.Tensor(~data, ms.float32)
print(new_data)
result = ops.ReduceSum()(new_data, 0)
print(result)
3 根因分析
new_data = ms.Tensor(~data, ms.float32)
如果需要转换Tensor的数据类型,建议使用Cast算子来进行操作。
不推荐使用Tensor( , <new_dtype>)修改Tensor的数据类型;使用Tensor()进行mindspore数据类型之间的转换可能会出错。
4 解决方案
修改代码如下,可得到预期输出:
import mindspore as ms
from mindspore import ops
data = ops.cast(ms.Tensor([[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]), ms.bool_)
print("data: \n", data)
print("inversed data: \n", ~data)
new_data = ops.cast(~data, ms.float32)
print("inversed data in float32:\n", new_data)
result = ops.ReduceSum()(new_data, 0)
print("result: \n", result)
data:
[[False False False False False False]
[ True True True True True True]
[ True True True True True True]]
inversed data:
[[ True True True True True True]
[False False False False False False]
[False False False False False False]]
inversed data in float32:
[[1. 1. 1. 1. 1. 1.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
result:
[1. 1. 1. 1. 1. 1.]
