from tensorflow.python.ops import array_ops

    # Sparse.
    if isinstance(tensor, ops.SparseTensorValue):
      tensor = ops.SparseTensor.from_value(tensor)
    if isinstance(tensor, ops.SparseTensor):
      if dim < 0:
        expand_dims = array_ops.reshape(
            array_ops.size(tensor.shape) + dim, [1])
      else:
        expand_dims = [dim]
      expanded_shape = array_ops.concat(
          0, (array_ops.slice(tensor.shape, [0], expand_dims), [1],
              array_ops.slice(tensor.shape, expand_dims, [-1])),
