Summarize a tensor by different methods.

    Args:
        x (tf.Tensor): a tensor to summarize
        types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms
        name (str): summary name. Defaults to be the op name.
        collections (list[str]): collections of the summary ops.
        main_tower_only (bool): Only run under main training tower. If
            set to True, calling this function under other TowerContext
            has no effect.

    Example:

    .. code-block:: python

        with tf.name_scope('mysummaries'):  # to not mess up tensorboard
            add_tensor_summary(
                tensor, ['histogram', 'rms', 'sparsity'], name='mytensor')

def add_tensor_summary(x, types, name=None, collections=None,
                       main_tower_only=True):
    """
    Summarize a tensor by different methods.

    Args:
        x (tf.Tensor): a tensor to summarize
        types (list[str]): summary types, can be scalar/histogram/sparsity/mean/rms
        name (str): summary name. Defaults to be the op name.
        collections (list[str]): collections of the summary ops.
        main_tower_only (bool): Only run under main training tower. If
            set to True, calling this function under other TowerContext
            has no effect.

    Example:

    .. code-block:: python

        with tf.name_scope('mysummaries'):  # to not mess up tensorboard
            add_tensor_summary(
                tensor, ['histogram', 'rms', 'sparsity'], name='mytensor')
    """
    types = set(types)
    if name is None:
        name = x.op.name
    ctx = get_current_tower_context()
    if main_tower_only and ctx is not None and not ctx.is_main_training_tower:
        return

    SUMMARY_TYPES_DIC = {
        'scalar': lambda: tf.summary.scalar(name + '-summary', x, collections=collections),
        'histogram': lambda: tf.summary.histogram(name + '-histogram', x, collections=collections),
        'sparsity': lambda: tf.summary.scalar(
            name + '-sparsity', tf.nn.zero_fraction(x),
            collections=collections),
        'mean': lambda: tf.summary.scalar(
            name + '-mean', tf.reduce_mean(x),
            collections=collections),
        'rms': lambda: tf.summary.scalar(
            name + '-rms', rms(x), collections=collections)
    }
    for typ in types:
        SUMMARY_TYPES_DIC[typ]()