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):
训练脚本是通过构建SoftmaxCrossEntropyWithLogits的单算子网络,计算两个变量softmax 交叉熵的例子。脚本如下:
01 class Net(nn.Cell):
02 def __init__(self):
03 super(Net, self).__init__()
04 self.loss = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
05
06 def construct(self, logits, labels):
07 output = self.loss(logits, labels)
08 return output
09
10 net = Net()
11 logits = Tensor(np.array([[[2, 4, 1, 4, 5], [2, 1, 2, 4, 3]]]), mindspore.float32)
12 labels = Tensor(np.array([[[0, 0, 0, 0, 1], [0, 0, 0, 1, 0]]]).astype(np.float32))
13 out = net(logits, labels)
14 print('out',out)
这里报错信息如下:
Traceback (most recent call last):
File "demo.py", line 13, in <module>
out = net(logits, labels)
…
ValueError: mindspore/core/utils/check_convert_utils.cc:395 CheckInteger] For primitive[SoftmaxCrossEntropyWithLogits], the dimension of logits must be equal to 2, but got 3.
The function call stack (See file ' rank_0/om/analyze_fail.dat' for more details):
\# 0 In file demo.py(04)
output = self.loss(logits, labels)
原因分析
在MindSpore 1.6版本,在construct中创建和使用Tensor。如脚本中第13行代码所示。
接着看报错信息,在ValueError中,写到For primitive[SoftmaxCrossEntropyWithLogits], the dimension of logits must be equal to 2, but got 3,意思是传的logits应该等于2维,但是你传进去的logits的shape却是3维,查看官网对logits的描述可知,支持的shape为(N,C)。
对于3维数据,建议先reshape成2维(N*L, C),然后再调用nn.SoftmaxCrossEntropyWithLogits接口,执行完后再reshape回 (N, 1)。
基于上面已知的原因,很容易做出如下修改:
1 class Net(nn.Cell):
2 def __init__(self):
3 super(Net, self).__init__()
4 self.loss = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
5
6 def construct(self, logits, labels):
7 output = self.loss(logits, labels)
8 return output
9
10 net = Net()
11 logits = Tensor(np.array([[[2, 4, 1, 4, 5], [2, 1, 2, 4, 3]]]), mindspore.float32)
12 labels = Tensor(np.array([[[0, 0, 0, 0, 1], [0, 0, 0, 1, 0]]]).astype(np.float32))
13 L, N, C = logits.shape
14 logits,labels = logits.reshape(L*N, C),labels.reshape(L*N, C)
15 out = net(logits, labels)
16 out = out.reshape(N,1)
17 print('out',out)
此时执行成功,输出如下:
out [[0.5899297 ]
[0.52374405]]
定位报错问题的步骤:
1、找到报错的用户代码行:out = net(logits, labels);
2、 根据日志报错信息中的关键字,缩小分析问题的范围the dimension of logits must be equal to 2, but got ;
3、需要重点关注变量定义、初始化的正确性。