How to fix tf.nn.in_top_k out of range issue: tensorflow.python.framework.errors_impl.InvalidArgumentError: targets[0] is out of range

tensorflow.python.framework.errors_impl.InvalidArgumentError: targets[0] is out of range
         [[Node: InTopK = InTopK[T=DT_INT32, k=1, _device="/job:localhost/replica:0/task:0/cpu:0"](softmax_linear/softmax_linear, Reshape_1)]]

Caused by op u'InTopK', defined at:




just simple codes like below:
    top_k_op = tf.nn.in_top_k(logits, labels, 1)

refer to tf.nn.in_top_k doc

  • predictions: A Tensor of type float32. A batch_size x classes tensor.
  • targets: A Tensor. Must be one of the following types: int32, int64. A batch_size vector of class ids.
The function will raise the error InvalidArgumentError: targets[i] is out of range when the element targets[i] is out of range (targets[i] > x)



For my case, the logits is [[-0.71366894  0.69218314]], the number of class is 2,
and labels is [147].With such case, I got the error InvalidArgumentError: targets[0] is out of range.
The two arguments are shape like:
predictions is Tensor("Reshape_1:0", shape=(1,), dtype=int32)
and targets is Tensor("softmax_linear/softmax_linear:0", shape=(1, 2), dtype=float32)
because targets[0] = 147 is out of range of predictions which has only shape 2.

The only cause for such error is that the data in targets(labels) out of range.
The solution is to correct the data in labels.
To confirm whether your labels correct or not, we can print the max one:

labels_max = tf.reduce_max(labels)
sess = tf.Session()
print sess.run(labels_max)


if labels_max > x(number of class), then we will encounter the same error again.


❤️ Support This Blog


If this post helped you, you can support my writing with a small donation. Thank you for reading.


Comments

Popular posts from this blog

fixed: embedded-redis: Unable to run on macOS Sonoma

Copying MDC Context Map in Web Clients: A Comprehensive Guide

Reset user password for your own Ghost blog