Home | History | Annotate | Download | only in ops
      1 # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
      2 #
      3 # Licensed under the Apache License, Version 2.0 (the "License");
      4 # you may not use this file except in compliance with the License.
      5 # You may obtain a copy of the License at
      6 #
      7 #     http://www.apache.org/licenses/LICENSE-2.0
      8 #
      9 # Unless required by applicable law or agreed to in writing, software
     10 # distributed under the License is distributed on an "AS IS" BASIS,
     11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 # See the License for the specific language governing permissions and
     13 # limitations under the License.
     14 # ==============================================================================
     15 # pylint: disable=g-short-docstring-punctuation
     16 """Histograms.
     17 
     18 Please see @{$python/histogram_ops} guide.
     19 
     20 @@histogram_fixed_width_bins
     21 @@histogram_fixed_width
     22 """
     23 
     24 from __future__ import absolute_import
     25 from __future__ import division
     26 from __future__ import print_function
     27 
     28 from tensorflow.python.framework import dtypes
     29 from tensorflow.python.framework import ops
     30 from tensorflow.python.ops import array_ops
     31 from tensorflow.python.ops import clip_ops
     32 from tensorflow.python.ops import gen_math_ops
     33 from tensorflow.python.ops import math_ops
     34 from tensorflow.python.util.tf_export import tf_export
     35 from tensorflow.python.util.tf_export import tf_export
     36 
     37 
     38 @tf_export('histogram_fixed_width_bins')
     39 def histogram_fixed_width_bins(values,
     40                                value_range,
     41                                nbins=100,
     42                                dtype=dtypes.int32,
     43                                name=None):
     44   """Bins the given values for use in a histogram.
     45 
     46   Given the tensor `values`, this operation returns a rank 1 `Tensor`
     47   representing the indices of a histogram into which each element
     48   of `values` would be binned. The bins are equal width and
     49   determined by the arguments `value_range` and `nbins`.
     50 
     51   Args:
     52     values:  Numeric `Tensor`.
     53     value_range:  Shape [2] `Tensor` of same `dtype` as `values`.
     54       values <= value_range[0] will be mapped to hist[0],
     55       values >= value_range[1] will be mapped to hist[-1].
     56     nbins:  Scalar `int32 Tensor`.  Number of histogram bins.
     57     dtype:  dtype for returned histogram.
     58     name:  A name for this operation (defaults to 'histogram_fixed_width').
     59 
     60   Returns:
     61     A `Tensor` holding the indices of the binned values whose shape matches
     62     `values`.
     63 
     64   Examples:
     65 
     66   ```python
     67   # Bins will be:  (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf)
     68   nbins = 5
     69   value_range = [0.0, 5.0]
     70   new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15]
     71 
     72   with tf.get_default_session() as sess:
     73     indices = tf.histogram_fixed_width_bins(new_values, value_range, nbins=5)
     74     variables.global_variables_initializer().run()
     75     sess.run(indices) => [0, 0, 1, 2, 4]
     76   ```
     77   """
     78   with ops.name_scope(name, 'histogram_fixed_width_bins',
     79                       [values, value_range, nbins]):
     80     values = ops.convert_to_tensor(values, name='values')
     81     shape = array_ops.shape(values)
     82 
     83     values = array_ops.reshape(values, [-1])
     84     value_range = ops.convert_to_tensor(value_range, name='value_range')
     85     nbins = ops.convert_to_tensor(nbins, dtype=dtypes.int32, name='nbins')
     86     nbins_float = math_ops.cast(nbins, values.dtype)
     87 
     88     # Map tensor values that fall within value_range to [0, 1].
     89     scaled_values = math_ops.truediv(
     90         values - value_range[0],
     91         value_range[1] - value_range[0],
     92         name='scaled_values')
     93 
     94     # map tensor values within the open interval value_range to {0,.., nbins-1},
     95     # values outside the open interval will be zero or less, or nbins or more.
     96     indices = math_ops.floor(nbins_float * scaled_values, name='indices')
     97 
     98     # Clip edge cases (e.g. value = value_range[1]) or "outliers."
     99     indices = math_ops.cast(
    100         clip_ops.clip_by_value(indices, 0, nbins_float - 1), dtypes.int32)
    101     return array_ops.reshape(indices, shape)
    102 
    103 
    104 @tf_export('histogram_fixed_width')
    105 def histogram_fixed_width(values,
    106                           value_range,
    107                           nbins=100,
    108                           dtype=dtypes.int32,
    109                           name=None):
    110   """Return histogram of values.
    111 
    112   Given the tensor `values`, this operation returns a rank 1 histogram counting
    113   the number of entries in `values` that fell into every bin.  The bins are
    114   equal width and determined by the arguments `value_range` and `nbins`.
    115 
    116   Args:
    117     values:  Numeric `Tensor`.
    118     value_range:  Shape [2] `Tensor` of same `dtype` as `values`.
    119       values <= value_range[0] will be mapped to hist[0],
    120       values >= value_range[1] will be mapped to hist[-1].
    121     nbins:  Scalar `int32 Tensor`.  Number of histogram bins.
    122     dtype:  dtype for returned histogram.
    123     name:  A name for this operation (defaults to 'histogram_fixed_width').
    124 
    125   Returns:
    126     A 1-D `Tensor` holding histogram of values.
    127 
    128   Examples:
    129 
    130   ```python
    131   # Bins will be:  (-inf, 1), [1, 2), [2, 3), [3, 4), [4, inf)
    132   nbins = 5
    133   value_range = [0.0, 5.0]
    134   new_values = [-1.0, 0.0, 1.5, 2.0, 5.0, 15]
    135 
    136   with tf.get_default_session() as sess:
    137     hist = tf.histogram_fixed_width(new_values, value_range, nbins=5)
    138     variables.global_variables_initializer().run()
    139     sess.run(hist) => [2, 1, 1, 0, 2]
    140   ```
    141   """
    142   with ops.name_scope(name, 'histogram_fixed_width',
    143                       [values, value_range, nbins]) as name:
    144     return gen_math_ops._histogram_fixed_width(  # pylint: disable=protected-access
    145         values, value_range, nbins, dtype=dtype, name=name)
    146