import tensorflow as tf

  # Note: tf.nn.softmax_cross_entropy_with_logits
  # expects logits, Keras expects probabilities.
  if not from_logits:
    epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
    output = tf.clip_by_value(output, epsilon, 1 - epsilon)
    output = tf.log(output)

  output_shape = output.get_shape()
  targets = cast(flatten(target), 'int64')
  logits = tf.reshape(output, [-1, int(output_shape[-1])])
  try:
    res = tf.nn.sparse_softmax_cross_entropy_with_logits(
        labels=targets, logits=logits)
  except TypeError:
    res = tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=targets)
  if len(output_shape) == 3:
    # if our output includes timesteps we need to reshape
    return tf.reshape(res, tf.shape(output)[:-1])
  else:
    return res


def binary_crossentropy(output, target, from_logits=False):
  """Binary crossentropy between an output tensor and a target tensor.

  # Arguments
      output: A tensor.
