title: Cost function training target versus accuracy desired goal
body: <p>When we train neural networks, we typically use gradient descent, which relies on a continuous, differentiable real-valued cost function. The final cost function might, for example, take the mean squared error. Or put another way, gradient descent implicitly assumes the end goal is <em>regression</em> - to minimize a real-valued error measure.</p>
  
  <p>Sometimes what we want a neural network to do is perform <em>classification</em> - given an input, classify it into two or more discrete categories. In this case, the end goal the user cares about is classification accuracy - the percentage of cases classified correctly.</p>
  
  <p>But when we are using a neural network for classification, though <em>our</em> goal is classification accuracy, <em>that is not what the neural network is trying to optimize</em>. The neural network is still trying to optimize the real-valued cost function. Sometimes these point in the same direction, but sometimes they don't. In particular, I've been running into cases where a neural network trained to correctly minimize the cost function, has a classification accuracy worse than a simple hand-coded threshold comparison.</p>
  
  <p>I've boiled this down to a minimal test case using TensorFlow. It sets up a perceptron (neural network with no hidden layers), trains it on an absolutely minimal dataset (one input variable, one binary output variable) assesses the classification accuracy of the result, then compares it to the classification accuracy of a simple hand-coded threshold comparison; the results are 60% and 80% respectively. Intuitively, this is because a single outlier with a large input value, generates a correspondingly large output value, so the way to minimize the cost function is to try extra hard to accommodate that one case, in the process misclassifying two more ordinary cases. The perceptron is correctly doing what it was told to do; it's just that this does not match what we actually want of a classifier. But the classification accuracy is not a continuous differentiable function, so we can't use it as the target for gradient descent.</p>
  
  <p>How can we train a neural network so that it ends up maximizing classification accuracy?</p>
  
  <pre><code>import numpy as np
  import tensorflow as tf
  sess = tf.InteractiveSession()
  tf.set_random_seed(1)
  
  # Parameters
  epochs = 10000
  learning_rate = 0.01
  
  # Data
  train_X = [
      [0],
      [0],
      [2],
      [2],
      [9],
  ]
  train_Y = [
      0,
      0,
      1,
      1,
      0,
  ]
  
  rows = np.shape(train_X)[0]
  cols = np.shape(train_X)[1]
  
  # Inputs and outputs
  X = tf.placeholder(tf.float32)
  Y = tf.placeholder(tf.float32)
  
  # Weights
  W = tf.Variable(tf.random_normal([cols]))
  b = tf.Variable(tf.random_normal([]))
  
  # Model
  pred = tf.tensordot(X, W, 1) + b
  cost = tf.reduce_sum((pred-Y)**2/rows)
  optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
  tf.global_variables_initializer().run()
  
  # Train
  for epoch in range(epochs):
      # Print update at successive doublings of time
      if epoch&amp;(epoch-1) == 0 or epoch == epochs-1:
          print('{} {} {} {}'.format(
              epoch,
              cost.eval({X: train_X, Y: train_Y}),
              W.eval(),
              b.eval(),
              ))
      optimizer.run({X: train_X, Y: train_Y})
  
  # Classification accuracy of perceptron
  classifications = [pred.eval({X: x}) &gt; 0.5 for x in train_X]
  correct = sum([p == y for (p, y) in zip(classifications, train_Y)])
  print('{}/{} = perceptron accuracy'.format(correct, rows))
  
  # Classification accuracy of hand-coded threshold comparison
  classifications = [x[0] &gt; 1.0 for x in train_X]
  correct = sum([p == y for (p, y) in zip(classifications, train_Y)])
  print('{}/{} = threshold accuracy'.format(correct, rows))
  </code></pre>