最近一直在看代码,也就是在改代码。众所周知,别人的代码就算复制到自己机器上,也还是运行不出来的。我称之为在学习思想~~
首先是烦人的动态图机制,要时刻记住你的代码其实默认并没有写进图里,当运行到的时候就已经执行了。先放一下我的错误,虽然都被我莫名其妙地解决了,但我不敢说自己懂了,我只能说这样好像,确实,是可以这样解决的。
下面是我出错提示,有需要的同学可以看一下
①
RuntimeError: `loss` passed to Optimizer.compute_gradients should be a function when eager execution is enabled.
如果问我最讨厌的Error,除了这个,就是那个没写进图的bug。其实理解起来不困难,就是需要输入一个函数,而不是一个值。我出错的代码如下,虽然这是一个平平无奇的损失函数~
def losses(logits, labels,learning_rate):
with tf.compat.v1.variable_scope('loss') as scope:
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels,
name='xentropy_per_example')
loss = tf.reduce_mean(cross_entropy, name='loss')
return loss
下面是对优化器需要输入的损失函数的要求
Eager Compatibility
When eager execution is enabled, loss should be a Python function that takes no
arguments and computes the value to be minimized. Minimization (and gradient
computation) is done with respect to the elements of var_list if not None, else with respect to any trainable variables created during the execution of the loss function. gate_gradients, aggregation_method, colocate_gradients_with_ops and grad_loss are ignored when eager execution is enabled.
发现需要的是是无参数的python函数,并且可以计算最小值。所以直接将上述损失函数改成无参的,将需要的数据直接进行带入就可以了。
②
ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables [] and loss <function loss at 0x000001CC93D12510>.
这个错误是没有找到需要梯度下降的variables ,既然它提示了损失函数,所以就从损失函数入手,这里不做详述,可以移步ValueError: No gradients provided for any variable进行查看,说白了,就是要让损失函数知道预测模型是什么样子。
③
这个错误是在使用tf.nn.sparse_softmax_cross_entropy_with_logits()
方法是出错的。
ValueError: Rank mismatch: Rank of labels (received 2) should equal rank of logits minus 1 (received 2).
其实这个比较简单,下面是对label的输入格式要求,会发现要求输入的标签应该是对应标签的索引,不要认为需要独热编码。
Tensor of shape [d_0, d_1, ..., d_{r-1}] (where r is rank of labels and result) and dtype int32 or int64. Each entry in labels must be an index in [0, num_classes).