MindSpore报错“For ‘Reshape‘, the shape of ‘input_x‘ is ...,but product“解决

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): Ubuntu 4.15.0-74-generic
– GCC/Compiler version (if compiled from source):

1.2 基本信息

1.2.1 脚本

脚本如下:

loc_data = mindspore.Tensor(np.random.randint(100, size=(1, 32760, 4)),mindspore.float32)
pos_idx = mindspore.Tensor(np.random.randint(2,size=(1, 32760, 4)),mindspore.int32)
pos_idx = ops.cast(pos_idx, mindspore.bool_)
loc_p = (ops.MaskedSelect()(loc_data, pos_idx))
loc_p = loc_p.view((-1,4))
print('result:',loc_p.shape)

1.2.2 报错

这里报错信息如下:

Traceback (most recent call last):
 File "demo.py", line 06, in <module>
loc_p = loc_p.view((-1,4)) 
…
ValueError: For 'Reshape', the shape of 'input_x' is [65209], the value of 'input_shape' value is [16302, 4]. The product of the shape of 'input_x' should be equal to product of 'input_shape', but product of the shape of 'input_x' is 65209, product of 'input_shape' is 65208.

原因分析

​ 我们来看报错信息,在ValueError中,写到The product of the shape of ‘input_x’ should be equal to product of ‘input_shape’,but product of the shape of ‘input_x’ is 65209, product of ‘input_shape’ is 65208,说的是产生的input_x的shape应该等于input_shape,但两者的值并不相等,这是由于MaskedSelect是一个动态shape算子,它每次输出的shape是根据input数据的不同而变化的,导致执行loc_p.view((-1,4))进行reshape操作的时候,大部分时候都不满足reshape成(-1,4)的条件,所以报错。

​ 遇到此类问题时,建议调整算法解决。

2 解决方法

基于上面已知的原因,可以进行丢弃小部分数据做出如下修改:
MindSpore报错“For ‘Reshape‘, the shape of ‘input_x‘ is ...,but product“解决_第1张图片

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

result:(16421, 4)

3 总结

定位报错问题的步骤:

1、到报错的用户代码行:loc_p = loc_p.view((-1,4))

2、 根据日志报错信息中的关键字,缩小分析问题的范围: The product of the shape of ‘input_x’ should be equal to product of ‘input_shape’;

3、 结合官网对API的相关介绍,查看传入到API时的参数是否符合要求;

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

5、 具体的解决办法得根据具体的场景进行操作。

4 参考文档

4.1 construct方法

你可能感兴趣的:(机器学习,神经网络)