from tensorflow.python.ops import math_ops

  # sparse_softmax_cross_entropy_with_logits requires [batch_size] target.
  if len(target.get_shape()) == 2:
    target = array_ops.squeeze(target, squeeze_dims=[1])
  loss_vec = nn.sparse_softmax_cross_entropy_with_logits(
      labels=target, logits=logits)
  return loss_vec


def _run_metrics(predictions, labels, metrics, weights):
  result = {}
  labels = math_ops.cast(labels, predictions.dtype)
  for name, metric in six.iteritems(metrics or {}):
    if weights is not None:
      result[name] = metric(predictions, labels, weights=weights)
    else:
      result[name] = metric(predictions, labels)

  return result


