Andrew Davidson
Andrew Davidson

Reputation: 37

tf.nn.softmax_cross_entropy_with_logits_v2 returing zero for MLP

I have made a 3 hidden layer MLP for a binary classifcation problem and am running into issues with my cost function. I am currently running on a small subset of data, the shape of which is (high number of features due to OHE):

x_train shape: (150, 1929)
y_train shape: (150, 1)
x_test shape: (51, 1929)
y_test shape: (51, 1)

And the tensowflow graph is:

# Parameters
learning_rate = 0.01
training_epochs = 500
iter_num = 500
batch_size = 200
display_step = training_epochs/10


# Network Parameters
n_hidden_1 = 1000 # 1st layer number of features
n_hidden_2 = 100 # 2nd layer number of features
n_hidden_3 = 8 # 3rd layer number of features
n_input = num_features # Number of input feature
n_classes = 1 # Number of classes to predict


# tf Graph input
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])

# Create model
def multilayer_perceptron(x, weights, biases):
    # Hidden layer with sigmoid activation function
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.sigmoid(layer_1)
    # Hidden layer with sigmoid activation function
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.sigmoid(layer_2)    
    #Hidden layer with sigmoid activation
    layer_3 = tf.add(tf.matmul(layer_2, weights['h3']), biases['b3'])
    layer_3 = tf.nn.sigmoid(layer_3)
    # Output layer with softmax activation
    out_layer = tf.matmul(layer_3, weights['out']) + biases['out']
    out_layer = tf.nn.softmax(out_layer)
    return out_layer

# Store layers weight & bias
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'h3': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_3])),
    'out': tf.Variable(tf.random_normal([n_hidden_3, n_classes]))
}

biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'b3': tf.Variable(tf.random_normal([n_hidden_3])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}


# Construct model
pred = multilayer_perceptron(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred, labels=y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)

correct = tf.cast(tf.equal(pred, y), dtype=tf.float32)
accuracy = tf.reduce_mean(tf.cast(correct, "float"))

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

I then run this graph with the code:

# Training loop
loss_vec = []
test_loss = []
train_acc = []
test_acc = []
predic = []

for epoch in range(iter_num):
    rand_index = np.random.choice(len(train_X), size=batch_size)
    rand_x = train_X[rand_index]
    rand_y = train_y[rand_index]

    temp_loss = sess.run(cost, feed_dict={x: rand_x,y: rand_y})    
    test_temp_loss = sess.run(cost, feed_dict={x: test_X, y: test_y})
    temp_train_acc = sess.run(accuracy, feed_dict={x: train_X, y: train_y})
    temp_test_acc = sess.run(accuracy, feed_dict={x: test_X, y: test_y})

    temp_prediction = sess.run(pred, feed_dict={x: test_X, y: test_y})
    predic.append(temp_prediction)

    loss_vec.append(np.sqrt(temp_loss))
    test_loss.append(np.sqrt(test_temp_loss))
    train_acc.append(temp_train_acc)
    test_acc.append(temp_test_acc)
    # output

    if (epoch + 1) % (iter_num/10) == 0:
        print('epoch: {:4d} loss: {:5f} train_acc: {:5f} test_acc: {:5f}'.format(epoch + 1, temp_loss,
                                                                          temp_train_acc, temp_test_acc))  

However, when I run this, the test and train accuracy remain constant, and the loss remains at zero, for all the epochs.

Output:

epoch:   50 loss: 0.000000 train_acc: 0.300000 test_acc: 0.235294
epoch:  100 loss: 0.000000 train_acc: 0.300000 test_acc: 0.235294
epoch:  150 loss: 0.000000 train_acc: 0.300000 test_acc: 0.235294
....

I cannot figure out why my loss is at zero? My target and predicition both seem to have the same shape and definitely are not equal.

Upvotes: 1

Views: 1179

Answers (1)

abhuse
abhuse

Reputation: 1086

tf.nn.softmax_cross_entropy_with_logits_v2 already computes softmax for you, you need to pass unbounded logits to your cross-entropy function, not the probability distribution that softmax returns. Try this:

def multilayer_perceptron(x, weights, biases):
    # ... 
    logits = tf.matmul(layer_3, weights['out']) + biases['out']
    out_layer = tf.nn.softmax(logits)
    return logits, out_layer

then use logits to compute cross-entropy and out_layer for inference.

logits, pred = multilayer_perceptron(x, weights, biases)
cost = tf.reduce_mean(
  tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y))

optimizer is the operation that calculates gradients and applies them to variables, this operation is essentially what makes your network "learn", you have declared it but I don't see you calling it inside the loop. This should do it:

_, temp_loss = sess.run([optimizer, cost], feed_dict={x: rand_x,y: rand_y})

You have a binary classification problem, I would guess your labels are either 0 or 1. You also have one output neuron, softmax of that will always return 1.0. What I would suggest is to make 2 output neurons, that way softmax will calculate probability distribution over 2 classes. Then your inference is the argmax of that distribution:

correct = tf.cast(tf.equal(tf.argmax(pred, 1), y), dtype=tf.float32)
accuracy = tf.reduce_mean(correct)

In this case, you need to use tf.nn.sparse_softmax_cross_entropy_with_logits() to calculate cross-entropy:

cost = tf.reduce_mean(
  tf.nn.tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y))

I would further suggest you to look at this post for more details on what I'm talking about.

Upvotes: 1

Related Questions