ValueError: Can not squeeze dim[1], expected a dimension of 1, got 3 for 'sparse_softmax_cross_entropy_loss

前端 未结 5 707
眼角桃花
眼角桃花 2020-12-09 15:18

I tried to replace the training and validation data with local images. But when running the training code, it came up with the error :

ValueError: Ca

5条回答
  •  一个人的身影
    2020-12-09 15:58

    The error here is from tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits).

    The TensorFlow documentation clearly states that "labels vector must provide a single specific index for the true class for each row of logits". So your labels vector must include only class-indices like 0,1,2 and not their respective one-hot-encodings like [1,0,0], [0,1,0], [0,0,1].

    Reproducing the error to explain further:

    import numpy as np
    import tensorflow as tf
    
    # Create random-array and assign as logits tensor
    np.random.seed(12345)
    logits = tf.convert_to_tensor(np.random.sample((4,4)))
    print logits.get_shape() #[4,4]
    
    # Create random-labels (Assuming only 4 classes)
    labels = tf.convert_to_tensor(np.array([2, 2, 0, 1]))
    
    loss_1 = tf.losses.sparse_softmax_cross_entropy(labels, logits)
    
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    
    print 'Loss: {}'.format(sess.run(loss_1)) # 1.44836854
    
    # Now giving one-hot-encodings in place of class-indices for labels
    wrong_labels = tf.convert_to_tensor(np.array([[0,0,1,0], [0,0,1,0], [1,0,0,0],[0,1,0,0]]))
    loss_2 = tf.losses.sparse_softmax_cross_entropy(wrong_labels, logits)
    
    # This should give you a similar error as soon as you define it
    

    So try giving class-indices instead of one-hot encodings in your Y_Labels vector. Hope this clears your doubt.

提交回复
热议问题