Python tensorflow.greater() Examples

The following are 30 code examples of tensorflow.greater(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tensorflow , or try the search function .
Example #1
Source File: box_list_ops_test.py    From object_detector_app with MIT License 6 votes vote down vote up
def test_visualize_boxes_in_image(self):
    image = tf.zeros((6, 4, 3))
    corners = tf.constant([[0, 0, 5, 3],
                           [0, 0, 3, 2]], tf.float32)
    boxes = box_list.BoxList(corners)
    image_and_boxes = box_list_ops.visualize_boxes_in_image(image, boxes)
    image_and_boxes_bw = tf.to_float(
        tf.greater(tf.reduce_sum(image_and_boxes, 2), 0.0))
    exp_result = [[1, 1, 1, 0],
                  [1, 1, 1, 0],
                  [1, 1, 1, 0],
                  [1, 0, 1, 0],
                  [1, 1, 1, 0],
                  [0, 0, 0, 0]]
    with self.test_session() as sess:
      output = sess.run(image_and_boxes_bw)
      self.assertAllEqual(output.astype(int), exp_result) 
Example #2
Source File: faster_rcnn_meta_arch.py    From vehicle_counting_tensorflow with MIT License 6 votes vote down vote up
def _get_refined_encodings_for_postitive_class(
      self, refined_box_encodings, flat_cls_targets_with_background,
      batch_size):
    # We only predict refined location encodings for the non background
    # classes, but we now pad it to make it compatible with the class
    # predictions
    refined_box_encodings_with_background = tf.pad(refined_box_encodings,
                                                   [[0, 0], [1, 0], [0, 0]])
    refined_box_encodings_masked_by_class_targets = (
        box_list_ops.boolean_mask(
            box_list.BoxList(
                tf.reshape(refined_box_encodings_with_background,
                           [-1, self._box_coder.code_size])),
            tf.reshape(tf.greater(flat_cls_targets_with_background, 0), [-1]),
            use_static_shapes=self._use_static_shapes,
            indicator_sum=batch_size * self.max_num_proposals
            if self._use_static_shapes else None).get())
    return tf.reshape(
        refined_box_encodings_masked_by_class_targets, [
            batch_size, self.max_num_proposals,
            self._box_coder.code_size
        ]) 
Example #3
Source File: colorizer.py    From HyperGAN with MIT License 6 votes vote down vote up
def apply_mask(gan, config, net,x=None):
    if x == None:
        x = gan.inputs.x
    filtered = net
    shape = gan.ops.shape(x)
    mask = tf.ones([shape[1], shape[2], shape[3]])
    mask = tf.greater(mask, 0)
    scaling = 0.6
    mask = tf.image.central_crop(mask, scaling)
    left = (shape[1]*scaling)//2 * 0.75
    top = (shape[2]*scaling)//2 * 0.75
    mask = tf.image.pad_to_bounding_box(mask, int(top), int(left), shape[1], shape[2])
    mask = tf.cast(mask, tf.float32)
    backmask = (1.0-mask) 
    filtered = backmask* x + mask * filtered
    print("FRAMING IMAGE", filtered) 
    return filtered 
Example #4
Source File: shape_utils.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def pad_or_clip_tensor(t, length):
  """Pad or clip the input tensor along the first dimension.

  Args:
    t: the input tensor, assuming the rank is at least 1.
    length: a tensor of shape [1]  or an integer, indicating the first dimension
      of the input tensor t after processing.

  Returns:
    processed_t: the processed tensor, whose first dimension is length. If the
      length is an integer, the first dimension of the processed tensor is set
      to length statically.
  """
  processed_t = tf.cond(
      tf.greater(tf.shape(t)[0], length),
      lambda: clip_tensor(t, length),
      lambda: pad_tensor(t, length))
  if not _is_tensor(length):
    processed_t = _set_dim_0(processed_t, length)
  return processed_t 
Example #5
Source File: faster_rcnn_meta_arch.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def _padded_batched_proposals_indicator(self,
                                          num_proposals,
                                          max_num_proposals):
    """Creates indicator matrix of non-pad elements of padded batch proposals.

    Args:
      num_proposals: Tensor of type tf.int32 with shape [batch_size].
      max_num_proposals: Maximum number of proposals per image (integer).

    Returns:
      A Tensor of type tf.bool with shape [batch_size, max_num_proposals].
    """
    batch_size = tf.size(num_proposals)
    tiled_num_proposals = tf.tile(
        tf.expand_dims(num_proposals, 1), [1, max_num_proposals])
    tiled_proposal_index = tf.tile(
        tf.expand_dims(tf.range(max_num_proposals), 0), [batch_size, 1])
    return tf.greater(tiled_num_proposals, tiled_proposal_index) 
Example #6
Source File: shape_utils.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def pad_tensor(t, length):
  """Pads the input tensor with 0s along the first dimension up to the length.

  Args:
    t: the input tensor, assuming the rank is at least 1.
    length: a tensor of shape [1]  or an integer, indicating the first dimension
      of the input tensor t after padding, assuming length <= t.shape[0].

  Returns:
    padded_t: the padded tensor, whose first dimension is length. If the length
      is an integer, the first dimension of padded_t is set to length
      statically.
  """
  t_rank = tf.rank(t)
  t_shape = tf.shape(t)
  t_d0 = t_shape[0]
  pad_d0 = tf.expand_dims(length - t_d0, 0)
  pad_shape = tf.cond(
      tf.greater(t_rank, 1), lambda: tf.concat([pad_d0, t_shape[1:]], 0),
      lambda: tf.expand_dims(length - t_d0, 0))
  padded_t = tf.concat([t, tf.zeros(pad_shape, dtype=t.dtype)], 0)
  if not _is_tensor(length):
    padded_t = _set_dim_0(padded_t, length)
  return padded_t 
Example #7
Source File: box_list_ops_test.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def test_visualize_boxes_in_image(self):
    image = tf.zeros((6, 4, 3))
    corners = tf.constant([[0, 0, 5, 3],
                           [0, 0, 3, 2]], tf.float32)
    boxes = box_list.BoxList(corners)
    image_and_boxes = box_list_ops.visualize_boxes_in_image(image, boxes)
    image_and_boxes_bw = tf.to_float(
        tf.greater(tf.reduce_sum(image_and_boxes, 2), 0.0))
    exp_result = [[1, 1, 1, 0],
                  [1, 1, 1, 0],
                  [1, 1, 1, 0],
                  [1, 0, 1, 0],
                  [1, 1, 1, 0],
                  [0, 0, 0, 0]]
    with self.test_session() as sess:
      output = sess.run(image_and_boxes_bw)
      self.assertAllEqual(output.astype(int), exp_result) 
Example #8
Source File: ops.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def retain_groundtruth_with_positive_classes(tensor_dict):
  """Retains only groundtruth with positive class ids.

  Args:
    tensor_dict: a dictionary of following groundtruth tensors -
      fields.InputDataFields.groundtruth_boxes
      fields.InputDataFields.groundtruth_classes
      fields.InputDataFields.groundtruth_is_crowd
      fields.InputDataFields.groundtruth_area
      fields.InputDataFields.groundtruth_label_types
      fields.InputDataFields.groundtruth_difficult

  Returns:
    a dictionary of tensors containing only the groundtruth with positive
    classes.

  Raises:
    ValueError: If groundtruth_classes tensor is not in tensor_dict.
  """
  if fields.InputDataFields.groundtruth_classes not in tensor_dict:
    raise ValueError('`groundtruth classes` not in tensor_dict.')
  keep_indices = tf.where(tf.greater(
      tensor_dict[fields.InputDataFields.groundtruth_classes], 0))
  return retain_groundtruth(tensor_dict, keep_indices) 
Example #9
Source File: faster_rcnn_meta_arch.py    From vehicle_counting_tensorflow with MIT License 6 votes vote down vote up
def _padded_batched_proposals_indicator(self,
                                          num_proposals,
                                          max_num_proposals):
    """Creates indicator matrix of non-pad elements of padded batch proposals.

    Args:
      num_proposals: Tensor of type tf.int32 with shape [batch_size].
      max_num_proposals: Maximum number of proposals per image (integer).

    Returns:
      A Tensor of type tf.bool with shape [batch_size, max_num_proposals].
    """
    batch_size = tf.size(num_proposals)
    tiled_num_proposals = tf.tile(
        tf.expand_dims(num_proposals, 1), [1, max_num_proposals])
    tiled_proposal_index = tf.tile(
        tf.expand_dims(tf.range(max_num_proposals), 0), [batch_size, 1])
    return tf.greater(tiled_num_proposals, tiled_proposal_index) 
Example #10
Source File: bulk_component.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def build_cross_entropy_loss(logits, gold):
  """Constructs a cross entropy from logits and one-hot encoded gold labels.

  Supports skipping rows where the gold label is the magic -1 value.

  Args:
    logits: float Tensor of scores.
    gold: int Tensor of one-hot labels.

  Returns:
    cost, correct, total: the total cost, the total number of correctly
        predicted labels, and the total number of valid labels.
  """
  valid = tf.reshape(tf.where(tf.greater(gold, -1)), [-1])
  gold = tf.gather(gold, valid)
  logits = tf.gather(logits, valid)
  correct = tf.reduce_sum(tf.to_int32(tf.nn.in_top_k(logits, gold, 1)))
  total = tf.size(gold)
  cost = tf.reduce_sum(
      tf.contrib.nn.deprecated_flipped_sparse_softmax_cross_entropy_with_logits(
          logits, tf.cast(gold, tf.int64))) / tf.cast(total, tf.float32)
  return cost, correct, total 
Example #11
Source File: box_list_ops_test.py    From vehicle_counting_tensorflow with MIT License 6 votes vote down vote up
def test_gather_with_dynamic_indexing(self):
    corners = tf.constant([4 * [0.0], 4 * [1.0], 4 * [2.0], 4 * [3.0], 4 * [4.0]
                          ])
    weights = tf.constant([.5, .3, .7, .1, .9], tf.float32)
    indices = tf.reshape(tf.where(tf.greater(weights, 0.4)), [-1])
    expected_subset = [4 * [0.0], 4 * [2.0], 4 * [4.0]]
    expected_weights = [.5, .7, .9]

    boxes = box_list.BoxList(corners)
    boxes.add_field('weights', weights)
    subset = box_list_ops.gather(boxes, indices, ['weights'])
    with self.test_session() as sess:
      subset_output, weights_output = sess.run([subset.get(), subset.get_field(
          'weights')])
      self.assertAllClose(subset_output, expected_subset)
      self.assertAllClose(weights_output, expected_weights) 
Example #12
Source File: ops.py    From vehicle_counting_tensorflow with MIT License 6 votes vote down vote up
def filter_groundtruth_with_nan_box_coordinates(tensor_dict):
  """Filters out groundtruth with no bounding boxes.

  Args:
    tensor_dict: a dictionary of following groundtruth tensors -
      fields.InputDataFields.groundtruth_boxes
      fields.InputDataFields.groundtruth_classes
      fields.InputDataFields.groundtruth_keypoints
      fields.InputDataFields.groundtruth_instance_masks
      fields.InputDataFields.groundtruth_is_crowd
      fields.InputDataFields.groundtruth_area
      fields.InputDataFields.groundtruth_label_types

  Returns:
    a dictionary of tensors containing only the groundtruth that have bounding
    boxes.
  """
  groundtruth_boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes]
  nan_indicator_vector = tf.greater(tf.reduce_sum(tf.to_int32(
      tf.is_nan(groundtruth_boxes)), reduction_indices=[1]), 0)
  valid_indicator_vector = tf.logical_not(nan_indicator_vector)
  valid_indices = tf.where(valid_indicator_vector)

  return retain_groundtruth(tensor_dict, valid_indices) 
Example #13
Source File: tf_example_decoder.py    From vehicle_counting_tensorflow with MIT License 6 votes vote down vote up
def _reshape_instance_masks(self, keys_to_tensors):
    """Reshape instance segmentation masks.

    The instance segmentation masks are reshaped to [num_instances, height,
    width].

    Args:
      keys_to_tensors: a dictionary from keys to tensors.

    Returns:
      A 3-D float tensor of shape [num_instances, height, width] with values
        in {0, 1}.
    """
    height = keys_to_tensors['image/height']
    width = keys_to_tensors['image/width']
    to_shape = tf.cast(tf.stack([-1, height, width]), tf.int32)
    masks = keys_to_tensors['image/object/mask']
    if isinstance(masks, tf.SparseTensor):
      masks = tf.sparse_tensor_to_dense(masks)
    masks = tf.reshape(tf.to_float(tf.greater(masks, 0.0)), to_shape)
    return tf.cast(masks, tf.float32) 
Example #14
Source File: jumpNormalAlgorithms.py    From decompose with MIT License 6 votes vote down vote up
def mode(cls, parameters: Dict[str, Tensor]) -> Tensor:
        mu = parameters["mu"]
        tau = parameters["tau"]
        nu = parameters["nu"]
        beta = parameters["beta"]

        lam = 1./beta
        mode = tf.zeros_like(mu) * tf.zeros_like(mu)
        mode = tf.where(tf.logical_and(tf.greater(nu, mu),
                                       tf.less(mu+lam/tau, nu)),
                        mu+lam/tau,
                        mode)
        mode = tf.where(tf.logical_and(tf.greater(nu, mu),
                                       tf.greater_equal(mu+lam/tau, nu)),
                        nu,
                        mode)
        mode = tf.where(tf.logical_and(tf.less_equal(nu, mu),
                                       tf.greater(mu-lam/tau, nu)),
                        mu-lam/tau,
                        mode)
        mode = tf.where(tf.logical_and(tf.less_equal(nu, mu),
                                       tf.less_equal(mu-lam/tau, nu)),
                        nu,
                        mode)
        return(mode) 
Example #15
Source File: path_context_reader.py    From code2vec with MIT License 6 votes vote down vote up
def _filter_input_rows(self, *row_parts) -> tf.bool:
        row_parts = self.model_input_tensors_former.from_model_input_form(row_parts)

        #assert all(tensor.shape == (self.config.MAX_CONTEXTS,) for tensor in
        #           {row_parts.path_source_token_indices, row_parts.path_indices,
        #            row_parts.path_target_token_indices, row_parts.context_valid_mask})

        # FIXME: Does "valid" here mean just "no padding" or "neither padding nor OOV"? I assumed just "no padding".
        any_word_valid_mask_per_context_part = [
            tf.not_equal(tf.reduce_max(row_parts.path_source_token_indices, axis=0),
                         self.vocabs.token_vocab.word_to_index[self.vocabs.token_vocab.special_words.PAD]),
            tf.not_equal(tf.reduce_max(row_parts.path_target_token_indices, axis=0),
                         self.vocabs.token_vocab.word_to_index[self.vocabs.token_vocab.special_words.PAD]),
            tf.not_equal(tf.reduce_max(row_parts.path_indices, axis=0),
                         self.vocabs.path_vocab.word_to_index[self.vocabs.path_vocab.special_words.PAD])]
        any_contexts_is_valid = reduce(tf.logical_or, any_word_valid_mask_per_context_part)  # scalar

        if self.estimator_action.is_evaluate:
            cond = any_contexts_is_valid  # scalar
        else:  # training
            word_is_valid = tf.greater(
                row_parts.target_index, self.vocabs.target_vocab.word_to_index[self.vocabs.target_vocab.special_words.OOV])  # scalar
            cond = tf.logical_and(word_is_valid, any_contexts_is_valid)  # scalar

        return cond  # scalar 
Example #16
Source File: ops.py    From object_detector_app with MIT License 6 votes vote down vote up
def retain_groundtruth_with_positive_classes(tensor_dict):
  """Retains only groundtruth with positive class ids.

  Args:
    tensor_dict: a dictionary of following groundtruth tensors -
      fields.InputDataFields.groundtruth_boxes
      fields.InputDataFields.groundtruth_classes
      fields.InputDataFields.groundtruth_is_crowd
      fields.InputDataFields.groundtruth_area
      fields.InputDataFields.groundtruth_label_types
      fields.InputDataFields.groundtruth_difficult

  Returns:
    a dictionary of tensors containing only the groundtruth with positive
    classes.

  Raises:
    ValueError: If groundtruth_classes tensor is not in tensor_dict.
  """
  if fields.InputDataFields.groundtruth_classes not in tensor_dict:
    raise ValueError('`groundtruth classes` not in tensor_dict.')
  keep_indices = tf.where(tf.greater(
      tensor_dict[fields.InputDataFields.groundtruth_classes], 0))
  return retain_groundtruth(tensor_dict, keep_indices) 
Example #17
Source File: ops.py    From object_detector_app with MIT License 6 votes vote down vote up
def filter_groundtruth_with_nan_box_coordinates(tensor_dict):
  """Filters out groundtruth with no bounding boxes.

  Args:
    tensor_dict: a dictionary of following groundtruth tensors -
      fields.InputDataFields.groundtruth_boxes
      fields.InputDataFields.groundtruth_classes
      fields.InputDataFields.groundtruth_is_crowd
      fields.InputDataFields.groundtruth_area
      fields.InputDataFields.groundtruth_label_types

  Returns:
    a dictionary of tensors containing only the groundtruth that have bounding
    boxes.
  """
  groundtruth_boxes = tensor_dict[fields.InputDataFields.groundtruth_boxes]
  nan_indicator_vector = tf.greater(tf.reduce_sum(tf.to_int32(
      tf.is_nan(groundtruth_boxes)), reduction_indices=[1]), 0)
  valid_indicator_vector = tf.logical_not(nan_indicator_vector)
  valid_indices = tf.where(valid_indicator_vector)

  return retain_groundtruth(tensor_dict, valid_indices) 
Example #18
Source File: shape_utils.py    From object_detector_app with MIT License 6 votes vote down vote up
def pad_tensor(t, length):
  """Pads the input tensor with 0s along the first dimension up to the length.

  Args:
    t: the input tensor, assuming the rank is at least 1.
    length: a tensor of shape [1]  or an integer, indicating the first dimension
      of the input tensor t after padding, assuming length <= t.shape[0].

  Returns:
    padded_t: the padded tensor, whose first dimension is length. If the length
      is an integer, the first dimension of padded_t is set to length
      statically.
  """
  t_rank = tf.rank(t)
  t_shape = tf.shape(t)
  t_d0 = t_shape[0]
  pad_d0 = tf.expand_dims(length - t_d0, 0)
  pad_shape = tf.cond(
      tf.greater(t_rank, 1), lambda: tf.concat([pad_d0, t_shape[1:]], 0),
      lambda: tf.expand_dims(length - t_d0, 0))
  padded_t = tf.concat([t, tf.zeros(pad_shape, dtype=t.dtype)], 0)
  if not _is_tensor(length):
    padded_t = _set_dim_0(padded_t, length)
  return padded_t 
Example #19
Source File: shape_utils.py    From object_detector_app with MIT License 6 votes vote down vote up
def pad_or_clip_tensor(t, length):
  """Pad or clip the input tensor along the first dimension.

  Args:
    t: the input tensor, assuming the rank is at least 1.
    length: a tensor of shape [1]  or an integer, indicating the first dimension
      of the input tensor t after processing.

  Returns:
    processed_t: the processed tensor, whose first dimension is length. If the
      length is an integer, the first dimension of the processed tensor is set
      to length statically.
  """
  processed_t = tf.cond(
      tf.greater(tf.shape(t)[0], length),
      lambda: clip_tensor(t, length),
      lambda: pad_tensor(t, length))
  if not _is_tensor(length):
    processed_t = _set_dim_0(processed_t, length)
  return processed_t 
Example #20
Source File: faster_rcnn_meta_arch.py    From object_detector_app with MIT License 6 votes vote down vote up
def _padded_batched_proposals_indicator(self,
                                          num_proposals,
                                          max_num_proposals):
    """Creates indicator matrix of non-pad elements of padded batch proposals.

    Args:
      num_proposals: Tensor of type tf.int32 with shape [batch_size].
      max_num_proposals: Maximum number of proposals per image (integer).

    Returns:
      A Tensor of type tf.bool with shape [batch_size, max_num_proposals].
    """
    batch_size = tf.size(num_proposals)
    tiled_num_proposals = tf.tile(
        tf.expand_dims(num_proposals, 1), [1, max_num_proposals])
    tiled_proposal_index = tf.tile(
        tf.expand_dims(tf.range(max_num_proposals), 0), [batch_size, 1])
    return tf.greater(tiled_num_proposals, tiled_proposal_index) 
Example #21
Source File: box_list_ops_test.py    From object_detector_app with MIT License 6 votes vote down vote up
def test_gather_with_dynamic_indexing(self):
    corners = tf.constant([4 * [0.0], 4 * [1.0], 4 * [2.0], 4 * [3.0], 4 * [4.0]
                          ])
    weights = tf.constant([.5, .3, .7, .1, .9], tf.float32)
    indices = tf.reshape(tf.where(tf.greater(weights, 0.4)), [-1])
    expected_subset = [4 * [0.0], 4 * [2.0], 4 * [4.0]]
    expected_weights = [.5, .7, .9]

    boxes = box_list.BoxList(corners)
    boxes.add_field('weights', weights)
    subset = box_list_ops.gather(boxes, indices, ['weights'])
    with self.test_session() as sess:
      subset_output, weights_output = sess.run([subset.get(), subset.get_field(
          'weights')])
      self.assertAllClose(subset_output, expected_subset)
      self.assertAllClose(weights_output, expected_weights) 
Example #22
Source File: losses.py    From R2CNN_Faster-RCNN_Tensorflow with MIT License 6 votes vote down vote up
def smooth_l1_loss_rpn(bbox_pred, bbox_targets, label, sigma=1.0):
    '''

    :param bbox_pred: [-1, 4]
    :param bbox_targets: [-1, 4]
    :param label: [-1]
    :param sigma:
    :return:
    '''
    value = _smooth_l1_loss_base(bbox_pred, bbox_targets, sigma=sigma)

    value = tf.reduce_sum(value, axis=1)  # to sum in axis 1

    # rpn_select = tf.reshape(tf.where(tf.greater_equal(label, 0)), [-1])
    rpn_select = tf.where(tf.greater(label, 0))

    # rpn_select = tf.stop_gradient(rpn_select) # to avoid
    selected_value = tf.gather(value, rpn_select)

    non_ignored_mask = tf.stop_gradient(
        1.0 - tf.to_float(tf.equal(label, -1)))  # positve is 1.0 others is 0.0

    bbox_loss = tf.reduce_sum(selected_value) / tf.maximum(1.0, tf.reduce_sum(non_ignored_mask))

    return bbox_loss 
Example #23
Source File: box_list_ops.py    From vehicle_counting_tensorflow with MIT License 5 votes vote down vote up
def prune_outside_window(boxlist, window, scope=None):
  """Prunes bounding boxes that fall outside a given window.

  This function prunes bounding boxes that even partially fall outside the given
  window. See also clip_to_window which only prunes bounding boxes that fall
  completely outside the window, and clips any bounding boxes that partially
  overflow.

  Args:
    boxlist: a BoxList holding M_in boxes.
    window: a float tensor of shape [4] representing [ymin, xmin, ymax, xmax]
      of the window
    scope: name scope.

  Returns:
    pruned_corners: a tensor with shape [M_out, 4] where M_out <= M_in
    valid_indices: a tensor with shape [M_out] indexing the valid bounding boxes
     in the input tensor.
  """
  with tf.name_scope(scope, 'PruneOutsideWindow'):
    y_min, x_min, y_max, x_max = tf.split(
        value=boxlist.get(), num_or_size_splits=4, axis=1)
    win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window)
    coordinate_violations = tf.concat([
        tf.less(y_min, win_y_min), tf.less(x_min, win_x_min),
        tf.greater(y_max, win_y_max), tf.greater(x_max, win_x_max)
    ], 1)
    valid_indices = tf.reshape(
        tf.where(tf.logical_not(tf.reduce_any(coordinate_violations, 1))), [-1])
    return gather(boxlist, valid_indices), valid_indices 
Example #24
Source File: llhImprovementThreshold.py    From decompose with MIT License 5 votes vote down vote up
def update(self, model, X: Tensor):
        llh = tf.cast(model.llh(X), tf.float64)
        llhOld = self.llhVar
        cond = tf.greater(self.llhImprovementThreshold, llh - llhOld)
        u0 = tf.assign(self.stopVar, cond)
        with tf.control_dependencies([u0]):
            u1 = tf.assign(self.llhVar, llh)
        return([u0, u1]) 
Example #25
Source File: preprocessor.py    From vehicle_counting_tensorflow with MIT License 5 votes vote down vote up
def random_rgb_to_gray(image,
                       probability=0.1,
                       seed=None,
                       preprocess_vars_cache=None):
  """Changes the image from RGB to Grayscale with the given probability.

  Args:
    image: rank 3 float32 tensor contains 1 image -> [height, width, channels]
           with pixel values varying between [0, 255].
    probability: the probability of returning a grayscale image.
            The probability should be a number between [0, 1].
    seed: random seed.
    preprocess_vars_cache: PreprocessorCache object that records previously
                           performed augmentations. Updated in-place. If this
                           function is called multiple times with the same
                           non-null cache, it will perform deterministically.

  Returns:
    image: image which is the same shape as input image.
  """
  def _image_to_gray(image):
    image_gray1 = _rgb_to_grayscale(image)
    image_gray3 = tf.image.grayscale_to_rgb(image_gray1)
    return image_gray3

  with tf.name_scope('RandomRGBtoGray', values=[image]):
    # random variable defining whether to change to grayscale or not
    generator_func = functools.partial(tf.random_uniform, [], seed=seed)
    do_gray_random = _get_or_create_preprocess_rand_vars(
        generator_func, preprocessor_cache.PreprocessorCache.RGB_TO_GRAY,
        preprocess_vars_cache)

    image = tf.cond(
        tf.greater(do_gray_random, probability), lambda: image,
        lambda: _image_to_gray(image))

  return image 
Example #26
Source File: box_list_ops.py    From vehicle_counting_tensorflow with MIT License 5 votes vote down vote up
def to_normalized_coordinates(boxlist, height, width,
                              check_range=True, scope=None):
  """Converts absolute box coordinates to normalized coordinates in [0, 1].

  Usually one uses the dynamic shape of the image or conv-layer tensor:
    boxlist = box_list_ops.to_normalized_coordinates(boxlist,
                                                     tf.shape(images)[1],
                                                     tf.shape(images)[2]),

  This function raises an assertion failed error at graph execution time when
  the maximum coordinate is smaller than 1.01 (which means that coordinates are
  already normalized). The value 1.01 is to deal with small rounding errors.

  Args:
    boxlist: BoxList with coordinates in terms of pixel-locations.
    height: Maximum value for height of absolute box coordinates.
    width: Maximum value for width of absolute box coordinates.
    check_range: If True, checks if the coordinates are normalized or not.
    scope: name scope.

  Returns:
    boxlist with normalized coordinates in [0, 1].
  """
  with tf.name_scope(scope, 'ToNormalizedCoordinates'):
    height = tf.cast(height, tf.float32)
    width = tf.cast(width, tf.float32)

    if check_range:
      max_val = tf.reduce_max(boxlist.get())
      max_assert = tf.Assert(tf.greater(max_val, 1.01),
                             ['max value is lower than 1.01: ', max_val])
      with tf.control_dependencies([max_assert]):
        width = tf.identity(width)

    return scale(boxlist, 1 / height, 1 / width) 
Example #27
Source File: box_list_ops.py    From vehicle_counting_tensorflow with MIT License 5 votes vote down vote up
def filter_greater_than(boxlist, thresh, scope=None):
  """Filter to keep only boxes with score exceeding a given threshold.

  This op keeps the collection of boxes whose corresponding scores are
  greater than the input threshold.

  TODO(jonathanhuang): Change function name to filter_scores_greater_than

  Args:
    boxlist: BoxList holding N boxes.  Must contain a 'scores' field
      representing detection scores.
    thresh: scalar threshold
    scope: name scope.

  Returns:
    a BoxList holding M boxes where M <= N

  Raises:
    ValueError: if boxlist not a BoxList object or if it does not
      have a scores field
  """
  with tf.name_scope(scope, 'FilterGreaterThan'):
    if not isinstance(boxlist, box_list.BoxList):
      raise ValueError('boxlist must be a BoxList')
    if not boxlist.has_field('scores'):
      raise ValueError('input boxlist must have \'scores\' field')
    scores = boxlist.get_field('scores')
    if len(scores.shape.as_list()) > 2:
      raise ValueError('Scores should have rank 1 or 2')
    if len(scores.shape.as_list()) == 2 and scores.shape.as_list()[1] != 1:
      raise ValueError('Scores should have rank 1 or have shape '
                       'consistent with [None, 1]')
    high_score_indices = tf.cast(tf.reshape(
        tf.where(tf.greater(scores, thresh)),
        [-1]), tf.int32)
    return gather(boxlist, high_score_indices) 
Example #28
Source File: nnNormalAlgorithms.py    From decompose with MIT License 5 votes vote down vote up
def mode(cls, parameters: Dict[str, Tensor]) -> Tensor:
        mu = parameters["mu"]
        mode = tf.where(tf.greater(mu, 0.), mu, tf.zeros_like(mu))
        return(mode) 
Example #29
Source File: tAlgorithms.py    From decompose with MIT License 5 votes vote down vote up
def fit(cls, parameters: Dict[str, Tensor],
            data: tf.Tensor) -> Dict[str, Tensor]:
        mu, Psi, nu = parameters["mu"], parameters["Psi"], parameters["nu"]

        p = 1.

        n = data.get_shape()[0].value
        Y = data
        for i in range(5):
            delta = (Y - mu)**2/Psi
            w = (nu + p)/(nu + delta)

            mu = tf.reduce_mean(w*Y, axis=0)
            PsiNew = tf.reduce_mean(w*(Y-mu)**2, axis=0)
            cond = tf.logical_and(tf.is_finite(PsiNew),
                                  tf.greater(PsiNew, 1e-6))
            Psi = tf.where(cond, PsiNew, Psi*tf.ones_like(PsiNew))

            delta = (Y - mu)**2/Psi
            nuNew = cls.nuStep(nu, n, delta)
            cond = tf.logical_and(tf.is_finite(nuNew),
                                  tf.greater(nuNew, 0.))
            nu = tf.where(cond, nuNew, nu*tf.ones_like(nuNew))

        tau = w
        updatedParameters = {"mu": mu, "nu": nu, "Psi": Psi, "tau": tau}
        return(updatedParameters) 
Example #30
Source File: jumpNormalAlgorithms.py    From decompose with MIT License 5 votes vote down vote up
def sample(cls, parameters: Dict[str, Tensor], nSamples: Tensor) -> Tensor:
        mu = parameters["mu"]
        tau = parameters["tau"]
        nu = parameters["nu"]
        beta = parameters["beta"]

        shape = tf.concat(((nSamples,), tf.shape(mu)), 0)
        ones = tf.ones(shape=shape, dtype=mu.dtype)
        mu = tf.reshape(mu*ones, (-1,))
        tau = tf.reshape(tau*ones, (-1,))
        nu = tf.reshape(nu*ones, (-1,))
        beta = tf.reshape(beta*ones, (-1,))
        inf = tf.reshape(tf.ones_like(mu)*tf.constant(np.inf, dtype=mu.dtype), (-1,))

        # sample from which side of the distribution to sample from
        alpha = cls.alpha(parameters)
        rUni = tf.random_uniform(shape=tf.shape(mu), dtype=mu.dtype)
        isRight = tf.greater(rUni, alpha)

        # sample from the left side
        rl = rtnorm(a=-inf,
                    b=nu,
                    mu=mu+1./(tau*beta),
                    sigma=1./tf.sqrt(tau))
        rl = tf.reshape(rl, (-1,))

        # sample from the right side
        rr = rtnorm(a=nu,
                    b=inf,
                    mu=mu-1./(tau*beta),
                    sigma=1./tf.sqrt(tau))
        rr = tf.reshape(rr, (-1,))

        # pick the samples randomly
        r = tf.where(isRight, rr, rl)

        # reshaping the samples
        r = tf.reshape(r, shape)
        return(r)