Matt
Matt

Reputation: 2350

tf.nn.softmax_cross_entropy_with_logits() error: logits and labels must be same size

I am new to TensorFlow and am trying to write an algorithm to classify images in the CIFAR-10 dataset. I am getting this error:

InvalidArgumentError (see above for traceback): logits and labels must be same size: logits_size=[10000,10] labels_size=[1,10000]
     [[Node: SoftmaxCrossEntropyWithLogits = SoftmaxCrossEntropyWithLogits[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](Reshape, Reshape_1)]]

Here is my code:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import cPickle

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100
image_size = 32*32*3 # because 3 channels

x = tf.placeholder('float', shape=(None, image_size)) 
y = tf.placeholder('float')

def neural_network_model(data):
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([image_size, n_nodes_hl1])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
    hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}
    output_layer = {'weights':tf.Variable(I am new to TensorFlow and tf.random_normal([n_nodes_hl3, n_classes])), 'biases':tf.Variable(tf.random_normal([n_classes]))}
    # input_data * weights + biases
    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases'])
    # activation function
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']
    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction, y))//THIS IS LINE 48 WHERE THE ERROR OCCURS
    #learning rate = 0.001
    optimizer = tf.train.AdamOptimizer().minimize(cost)
    hm_epochs = 10
    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())
        for epoch in range(hm_epochs):
            epoch_loss = 0
            for i in range(5):
                with open('data_batch_'+str(i+1),'rb') as f:
                    train_data = cPickle.load(f)
                print train_data
                print prediction.get_shape()
                #print len(y)
                _, c = sess.run([optimizer, cost], feed_dict={x:train_data['data'],y:train_data['labels']})
                epoch_loss += c
            print 'Epoch ' + str(epoch) + ' completed out of ' + str(hm_epochs) + ' loss: ' + str(epoch_loss)
        correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        with open('test_batch','rb') as f:
            test_data = cPickle.load(f)
            accuracy = accuracy.eval({x:test_data['data'],y:test_data['labels']})
        print 'Accuracy: ' + str(accuracy)

train_neural_network(x)

I'm pretty sure this means that in line 48 (shown above) prediction and y are not the same shape, but I don't understand TensorFlow well enough to know how to fix it. I don't even really understand where y is being set, I got most of this code from a tutorial and fiddled with it to apply it to a different dataset. How can I fix this error?

Upvotes: 0

Views: 6146

Answers (2)

Rizky Yoga Oktora
Rizky Yoga Oktora

Reputation: 39

Here are some updates to the code to support TensorFlow version 1.0:

def train_neural_network(x):
    prediction = neural_network_model(x)
    #OLD VERSION:
    #cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) )
    #NEW:
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )
    optimizer = tf.train.AdamOptimizer().minimize(cost)
    hm_epochs = 10
    with tf.Session() as sess:
        #OLD: 
        #sess.run(tf.initialize_all_variables())
        #NEW:
        sess.run(tf.global_variables_initializer())

Upvotes: 1

mrry
mrry

Reputation: 126154

The tf.nn.softmax_cross_entropy_with_logits(logits, labels) op expects its logits and labels arguments to be tensors with the same shape. Furthermore, the logits and labels arguments should be 2-D tensors (matrices) with batch_size rows, and num_classes columns.

From the error message and the size of logits, I'm guessing that batch_size is 10000, and num_classes is 10. From the size of labels, I'm guessing that your labels are encoded as a list of integers, where the integer represent the index of the class for the corresponding input example. (I'd have expected this to be a tf.int32 value, rather than tf.float32 as it appears to be in your program, but perhaps there is some automatic conversion going on.)

In TensorFlow, you can use the tf.nn.sparse_softmax_cross_entropy_with_logits() to compute cross-entropy on data in this form. In your program, you could do this by replacing the cost calculation with:

cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
    prediction, tf.squeeze(y)))

Note that the tf.squeeze() op is needed to convert y into a vector of length batch_size (in order to be a valid argument to tf.nn.sparse_softmax_cross_entropy_with_logits().

Upvotes: 2

Related Questions