Python tensorflow.floordiv() Examples

The following are 30 code examples of tensorflow.floordiv(). 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: discretization.py    From training_results_v0.5 with Apache License 2.0 6 votes vote down vote up
def int_to_bit(x_int, num_bits, base=2):
  """Turn x_int representing numbers into a bitwise (lower-endian) tensor.

  Args:
    x_int: Tensor containing integer to be converted into base notation.
    num_bits: Number of bits in the representation.
    base: Base of the representation.

  Returns:
    Corresponding number expressed in base.
  """
  x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
  x_labels = []
  for i in range(num_bits):
    x_labels.append(
        tf.floormod(
            tf.floordiv(tf.to_int32(x_l),
                        tf.to_int32(base)**i), tf.to_int32(base)))
  res = tf.concat(x_labels, axis=-1)
  return tf.to_float(res) 
Example #2
Source File: feedback.py    From sequencing with MIT License 6 votes vote down vote up
def sample(self, logits, time):
        rl_time_steps = tf.floordiv(tf.maximum(self.global_step_tensor -
                                               self.burn_in_step, 0),
                                    self.increment_step)
        start_rl_step = self.sequence_length - rl_time_steps

        next_input_ids = tf.cond(
            tf.greater_equal(time, self.max_sequence_length),
            lambda: tf.tile([self.eos_id], [self.batch_size]),
            lambda: self._input_tas.read(time))

        next_predicted_ids = tf.squeeze(tf.multinomial(logits, 1), axis=[-1])
        mask = tf.to_int32(time >= start_rl_step)

        return (1 - mask) * tf.to_int32(next_input_ids) + mask * tf.to_int32(
            next_predicted_ids) 
Example #3
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def _testBCastByFunc(self, funcs, xs, ys):
    dtypes = [
        np.float16,
        np.float32,
        np.float64,
        np.int32,
        np.int64,
        np.complex64,
        np.complex128,
    ]
    for dtype in dtypes:
      for (np_func, tf_func) in funcs:
        if (dtype in (np.complex64, np.complex128) and
              tf_func in (_FLOORDIV, tf.floordiv)):
          continue  # floordiv makes no sense for complex numbers
        self._compareBCast(xs, ys, dtype, np_func, tf_func)
        self._compareBCast(ys, xs, dtype, np_func, tf_func) 
Example #4
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def _compareBCast(self, xs, ys, dtype, np_func, tf_func):
    if dtype in (np.complex64, np.complex128):
      x = (1 + np.linspace(0, 2 + 3j, np.prod(xs))).astype(dtype).reshape(xs)
      y = (1 + np.linspace(0, 2 - 2j, np.prod(ys))).astype(dtype).reshape(ys)
    else:
      x = (1 + np.linspace(0, 5, np.prod(xs))).astype(dtype).reshape(xs)
      y = (1 + np.linspace(0, 5, np.prod(ys))).astype(dtype).reshape(ys)
    self._compareCpu(x, y, np_func, tf_func)
    if x.dtype in (np.float16, np.float32, np.float64, np.complex64,
                   np.complex128):
      if tf_func not in (_FLOORDIV, tf.floordiv):
        if x.dtype == np.float16:
          # Compare fp16 theoretical gradients to fp32 numerical gradients,
          # since fp16 numerical gradients are too imprecise unless great
          # care is taken with choosing the inputs and the delta. This is
          # a weaker check (in particular, it does not test the op itself,
          # only its gradient), but it's much better than nothing.
          self._compareGradientX(x, y, np_func, tf_func, np.float)
          self._compareGradientY(x, y, np_func, tf_func, np.float)
        else:
          self._compareGradientX(x, y, np_func, tf_func)
          self._compareGradientY(x, y, np_func, tf_func)
      self._compareGpu(x, y, np_func, tf_func)

  # TODO(josh11b,vrv): Refactor this to use parameterized tests. 
Example #5
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def testInt32Basic(self):
    x = np.arange(1, 13, 2).reshape(1, 3, 2).astype(np.int32)
    y = np.arange(1, 7, 1).reshape(1, 3, 2).astype(np.int32)
    self._compareBoth(x, y, np.add, tf.add)
    self._compareBoth(x, y, np.subtract, tf.sub)
    self._compareBoth(x, y, np.multiply, tf.mul)
    self._compareBoth(x, y, np.true_divide, tf.truediv)
    self._compareBoth(x, y, np.floor_divide, tf.floordiv)
    self._compareBoth(x, y, np.mod, tf.mod)
    self._compareBoth(x, y, np.add, _ADD)
    self._compareBoth(x, y, np.subtract, _SUB)
    self._compareBoth(x, y, np.multiply, _MUL)
    self._compareBoth(x, y, np.true_divide, _TRUEDIV)
    self._compareBoth(x, y, np.floor_divide, _FLOORDIV)
    self._compareBoth(x, y, np.mod, _MOD)
    # _compareBoth tests on GPU only for floating point types, so test
    # _MOD for int32 on GPU by calling _compareGpu
    self._compareGpu(x, y, np.mod, _MOD) 
Example #6
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def testDoubleBasic(self):
    x = np.linspace(-5, 20, 15).reshape(1, 3, 5).astype(np.float64)
    y = np.linspace(20, -5, 15).reshape(1, 3, 5).astype(np.float64)
    self._compareBoth(x, y, np.add, tf.add)
    self._compareBoth(x, y, np.subtract, tf.sub)
    self._compareBoth(x, y, np.multiply, tf.mul)
    self._compareBoth(x, y + 0.1, np.true_divide, tf.truediv)
    self._compareBoth(x, y + 0.1, np.floor_divide, tf.floordiv)
    self._compareBoth(x, y, np.add, _ADD)
    self._compareBoth(x, y, np.subtract, _SUB)
    self._compareBoth(x, y, np.multiply, _MUL)
    self._compareBoth(x, y + 0.1, np.true_divide, _TRUEDIV)
    self._compareBoth(x, y + 0.1, np.floor_divide, _FLOORDIV)
    try:
      from scipy import special  # pylint: disable=g-import-not-at-top
      a_pos_small = np.linspace(0.1, 2, 15).reshape(1, 3, 5).astype(np.float32)
      x_pos_small = np.linspace(0.1, 10, 15).reshape(1, 3, 5).astype(np.float32)
      self._compareBoth(a_pos_small, x_pos_small, special.gammainc, tf.igamma)
      self._compareBoth(a_pos_small, x_pos_small, special.gammaincc, tf.igammac)
    except ImportError as e:
      tf.logging.warn("Cannot test special functions: %s" % str(e)) 
Example #7
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def testFloatBasic(self):
    x = np.linspace(-5, 20, 15).reshape(1, 3, 5).astype(np.float32)
    y = np.linspace(20, -5, 15).reshape(1, 3, 5).astype(np.float32)
    self._compareBoth(x, y, np.add, tf.add, also_compare_variables=True)
    self._compareBoth(x, y, np.subtract, tf.sub)
    self._compareBoth(x, y, np.multiply, tf.mul)
    self._compareBoth(x, y + 0.1, np.true_divide, tf.truediv)
    self._compareBoth(x, y + 0.1, np.floor_divide, tf.floordiv)
    self._compareBoth(x, y, np.add, _ADD)
    self._compareBoth(x, y, np.subtract, _SUB)
    self._compareBoth(x, y, np.multiply, _MUL)
    self._compareBoth(x, y + 0.1, np.true_divide, _TRUEDIV)
    self._compareBoth(x, y + 0.1, np.floor_divide, _FLOORDIV)
    try:
      from scipy import special  # pylint: disable=g-import-not-at-top
      a_pos_small = np.linspace(0.1, 2, 15).reshape(1, 3, 5).astype(np.float32)
      x_pos_small = np.linspace(0.1, 10, 15).reshape(1, 3, 5).astype(np.float32)
      self._compareBoth(a_pos_small, x_pos_small, special.gammainc, tf.igamma)
      self._compareBoth(a_pos_small, x_pos_small, special.gammaincc, tf.igammac)
      # Need x > 1
      self._compareBoth(x_pos_small + 1, a_pos_small, special.zeta, tf.zeta)
      n_small = np.arange(0, 15).reshape(1, 3, 5).astype(np.float32)
      self._compareBoth(n_small, x_pos_small, special.polygamma, tf.polygamma)
    except ImportError as e:
      tf.logging.warn("Cannot test special functions: %s" % str(e)) 
Example #8
Source File: preprocessing.py    From Real-time-self-adaptive-deep-stereo with Apache License 2.0 6 votes vote down vote up
def pad_image(immy,down_factor = 256,dynamic=False):
    """
    pad image with a proper number of 0 to prevent problem when concatenating after upconv
    Args:
        immy: metaop that produces an image
        down_factor: downgrade resolution that should be respected before feeding the image to the network
        dynamic: if dynamic is True use dynamic shape of immy, otherway use static shape
    """
    if dynamic:
        immy_shape = tf.shape(immy)
        new_height = tf.where(tf.equal(immy_shape[-3]%down_factor,0),x=immy_shape[-3],y=(tf.floordiv(immy_shape[-3],down_factor)+1)*down_factor)
        new_width = tf.where(tf.equal(immy_shape[-2]%down_factor,0),x=immy_shape[-2],y=(tf.floordiv(immy_shape[-2],down_factor)+1)*down_factor)
    else:
        immy_shape = immy.get_shape().as_list()
        new_height = immy_shape[-3] if immy_shape[-3]%down_factor==0 else ((immy_shape[-3]//down_factor)+1)*down_factor
        new_width = immy_shape[-2] if immy_shape[-2]%down_factor==0 else ((immy_shape[-2]//down_factor)+1)*down_factor
    
    pad_height_left = (new_height-immy_shape[-3])//2
    pad_height_right = (new_height-immy_shape[-3]+1)//2
    pad_width_left = (new_width-immy_shape[-2])//2
    pad_width_right = (new_width-immy_shape[-2]+1)//2
    immy = tf.pad(immy,[[0,0],[pad_height_left,pad_height_right],[pad_width_left,pad_width_right],[0,0]],mode="REFLECT")
    return immy 
Example #9
Source File: discretization.py    From acai with Apache License 2.0 6 votes vote down vote up
def int_to_bit(self, x_int, num_bits, base=2):

        """Turn x_int representing numbers into a bitwise (lower-endian)
        tensor.

        Args:
            x_int: Tensor containing integer to be converted into base
            notation.
            num_bits: Number of bits in the representation.
            base: Base of the representation.

        Returns:
            Corresponding number expressed in base.
        """
        x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
        x_labels = []
        for i in range(num_bits):
            x_labels.append(
                tf.floormod(
                    tf.floordiv(tf.to_int32(x_l),
                                tf.to_int32(base) ** i), tf.to_int32(base)))
        res = tf.concat(x_labels, axis=-1)
        return tf.to_float(res) 
Example #10
Source File: vq_discrete.py    From training_results_v0.5 with Apache License 2.0 6 votes vote down vote up
def int_to_bit(self, x_int, num_bits, base=2):
    """Turn x_int representing numbers into a bitwise (lower-endian) tensor.

    Args:
        x_int: Tensor containing integer to be converted into base
        notation.
        num_bits: Number of bits in the representation.
        base: Base of the representation.

    Returns:
        Corresponding number expressed in base.
    """
    x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
    x_labels = []
    for i in range(num_bits):
      x_labels.append(
          tf.floormod(
              tf.floordiv(tf.to_int32(x_l),
                          tf.to_int32(base)**i), tf.to_int32(base)))
    res = tf.concat(x_labels, axis=-1)
    return tf.to_float(res) 
Example #11
Source File: ops.py    From listen-attend-and-spell with Apache License 2.0 6 votes vote down vote up
def pyramidal_stack(outputs, sequence_length):
    shape = tf.shape(outputs)
    batch_size, max_time = shape[0], shape[1]
    num_units = outputs.get_shape().as_list()[-1]
    paddings = [[0, 0], [0, tf.floormod(max_time, 2)], [0, 0]]
    outputs = tf.pad(outputs, paddings)

    '''
    even_time = outputs[:, ::2, :]
    odd_time = outputs[:, 1::2, :]

    concat_outputs = tf.concat([even_time, odd_time], -1)
    '''

    concat_outputs = tf.reshape(outputs, (batch_size, -1, num_units * 2))

    return concat_outputs, tf.floordiv(sequence_length, 2) + tf.floormod(sequence_length, 2) 
Example #12
Source File: discretization.py    From BERT with Apache License 2.0 6 votes vote down vote up
def int_to_bit(x_int, num_bits, base=2):
  """Turn x_int representing numbers into a bitwise (lower-endian) tensor.

  Args:
    x_int: Tensor containing integer to be converted into base notation.
    num_bits: Number of bits in the representation.
    base: Base of the representation.

  Returns:
    Corresponding number expressed in base.
  """
  x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
  x_labels = [tf.floormod(
      tf.floordiv(tf.to_int32(x_l), tf.to_int32(base)**i), tf.to_int32(base))
              for i in range(num_bits)]
  res = tf.concat(x_labels, axis=-1)
  return tf.to_float(res) 
Example #13
Source File: vq_discrete.py    From BERT with Apache License 2.0 6 votes vote down vote up
def int_to_bit(self, x_int, num_bits, base=2):
    """Turn x_int representing numbers into a bitwise (lower-endian) tensor.

    Args:
        x_int: Tensor containing integer to be converted into base
        notation.
        num_bits: Number of bits in the representation.
        base: Base of the representation.

    Returns:
        Corresponding number expressed in base.
    """
    x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
    # pylint: disable=g-complex-comprehension
    x_labels = [
        tf.floormod(
            tf.floordiv(tf.to_int32(x_l),
                        tf.to_int32(base)**i), tf.to_int32(base))
        for i in range(num_bits)]
    res = tf.concat(x_labels, axis=-1)
    return tf.to_float(res) 
Example #14
Source File: preprocessing.py    From Learning2AdaptForStereo with Apache License 2.0 6 votes vote down vote up
def pad_image(immy,down_factor = 256,dynamic=False):
    """
    pad image with a proper number of 0 to prevent problem when concatenating after upconv
    Args:
        immy: metaop that produces an image
        down_factor: downgrade resolution that should be respected before feeding the image to the network
        dynamic: if dynamic is True use dynamic shape of immy, otherway use static shape
    """
    if dynamic:
        immy_shape = tf.shape(immy)
        new_height = tf.where(tf.equal(immy_shape[-3]%down_factor,0),x=immy_shape[-3],y=(tf.floordiv(immy_shape[-3],down_factor)+1)*down_factor)
        new_width = tf.where(tf.equal(immy_shape[-2]%down_factor,0),x=immy_shape[-2],y=(tf.floordiv(immy_shape[-2],down_factor)+1)*down_factor)
    else:
        immy_shape = immy.get_shape().as_list()
        new_height = immy_shape[-3] if immy_shape[-3]%down_factor==0 else ((immy_shape[-3]//down_factor)+1)*down_factor
        new_width = immy_shape[-2] if immy_shape[-2]%down_factor==0 else ((immy_shape[-2]//down_factor)+1)*down_factor
    
    pad_height_left = (new_height-immy_shape[-3])//2
    pad_height_right = (new_height-immy_shape[-3]+1)//2
    pad_width_left = (new_width-immy_shape[-2])//2
    pad_width_right = (new_width-immy_shape[-2]+1)//2
    immy = tf.pad(immy,[[0,0],[pad_height_left,pad_height_right],[pad_width_left,pad_width_right],[0,0]],mode="REFLECT")
    return immy 
Example #15
Source File: discretization.py    From fine-lm with MIT License 6 votes vote down vote up
def int_to_bit(x_int, num_bits, base=2):
  """Turn x_int representing numbers into a bitwise (lower-endian) tensor.

  Args:
    x_int: Tensor containing integer to be converted into base notation.
    num_bits: Number of bits in the representation.
    base: Base of the representation.

  Returns:
    Corresponding number expressed in base.
  """
  x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
  x_labels = []
  for i in range(num_bits):
    x_labels.append(
        tf.floormod(
            tf.floordiv(tf.to_int32(x_l),
                        tf.to_int32(base)**i), tf.to_int32(base)))
  res = tf.concat(x_labels, axis=-1)
  return tf.to_float(res) 
Example #16
Source File: tensorflow_backend.py    From keras-contrib with MIT License 5 votes vote down vote up
def extract_image_patches(x, ksizes, ssizes, padding='same',
                          data_format='channels_last'):
    """Extract the patches from an image.

    # Arguments
        x: The input image
        ksizes: 2-d tuple with the kernel size
        ssizes: 2-d tuple with the strides size
        padding: 'same' or 'valid'
        data_format: 'channels_last' or 'channels_first'

    # Returns
        The (k_w,k_h) patches extracted
        TF ==> (batch_size,w,h,k_w,k_h,c)
        TH ==> (batch_size,w,h,c,k_w,k_h)
    """
    kernel = [1, ksizes[0], ksizes[1], 1]
    strides = [1, ssizes[0], ssizes[1], 1]
    padding = _preprocess_padding(padding)
    if data_format == 'channels_first':
        x = K.permute_dimensions(x, (0, 2, 3, 1))
    bs_i, w_i, h_i, ch_i = K.int_shape(x)
    patches = tf.extract_image_patches(x, kernel, strides, [1, 1, 1, 1],
                                       padding)
    # Reshaping to fit Theano
    bs, w, h, ch = K.int_shape(patches)
    reshaped = tf.reshape(patches, [-1, w, h, tf.floordiv(ch, ch_i), ch_i])
    final_shape = [-1, w, h, ch_i, ksizes[0], ksizes[1]]
    patches = tf.reshape(tf.transpose(reshaped, [0, 1, 2, 4, 3]), final_shape)
    if data_format == 'channels_last':
        patches = K.permute_dimensions(patches, [0, 1, 2, 4, 5, 3])
    return patches 
Example #17
Source File: model.py    From mac-network with Apache License 2.0 5 votes vote down vote up
def initTowerBatch(self, towerI, towersNum, dataSize):
        towerBatchSize = tf.floordiv(dataSize, towersNum)
        start = towerI * towerBatchSize
        end = (towerI + 1) * towerBatchSize if towerI < towersNum - 1 else dataSize

        self.questionsIndices = self.questionsIndicesAll[start:end]
        self.questionLengths = self.questionLengthsAll[start:end]
        self.images = self.imagesAll[start:end]
        self.answersIndices = self.answersIndicesAll[start:end]

        self.batchSize = end - start 
Example #18
Source File: ops.py    From Live-feed-object-device-identification-using-Tensorflow-and-OpenCV with Apache License 2.0 5 votes vote down vote up
def fpn_feature_levels(num_levels, unit_scale_index, image_ratio, boxes):
  """Returns fpn feature level for each box based on its area.

  See section 4.2 of https://arxiv.org/pdf/1612.03144.pdf for details.

  Args:
    num_levels: An integer indicating the number of feature levels to crop boxes
      from.
    unit_scale_index: An 0-based integer indicating the index of feature map
      which most closely matches the resolution of the pretrained model.
    image_ratio: A float indicating the ratio of input image area to pretraining
      image area.
    boxes: A float tensor of shape [batch, num_boxes, 4] containing boxes of the
      form [ymin, xmin, ymax, xmax] in normalized coordinates.

  Returns:
    An int32 tensor of shape [batch_size, num_boxes] containing feature indices.
  """
  assert num_levels > 0, (
      '`num_levels` must be > 0. Found {}'.format(num_levels))
  assert unit_scale_index < num_levels and unit_scale_index >= 0, (
      '`unit_scale_index` must be in [0, {}). Found {}.'.format(
          num_levels, unit_scale_index))
  box_height_width = boxes[:, :, 2:4] - boxes[:, :, 0:2]
  areas_sqrt = tf.sqrt(tf.reduce_prod(box_height_width, axis=2))
  log_2 = tf.cast(tf.log(2.0), dtype=boxes.dtype)
  levels = tf.cast(
      tf.floordiv(tf.log(areas_sqrt * image_ratio), log_2)
      +
      unit_scale_index,
      dtype=tf.int32)
  levels = tf.maximum(0, tf.minimum(num_levels - 1, levels))
  return levels 
Example #19
Source File: model.py    From lcgn with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def init_tower_batch(self, towerI, towersNum, dataSize):
        towerBatchSize = tf.floordiv(dataSize, towersNum)
        start = towerI * towerBatchSize
        end = (towerI+1)*towerBatchSize if towerI < towersNum-1 else dataSize

        self.questionIndices = self.questionIndicesAll[start:end]
        self.questionLengths = self.questionLengthsAll[start:end]
        self.images = self.imagesAll[start:end]
        self.imagesObjectNum = self.imagesObjectNumAll[start:end]
        if cfg.BUILD_VQA:
            self.answerIndices = self.answerIndicesAll[start:end]
        if cfg.BUILD_REF:
            self.bboxIndGt = self.bboxIndGtAll[start:end]
            self.bboxOffsetGt = self.bboxOffsetGtAll[start:end]
        self.batchSize = end - start 
Example #20
Source File: model.py    From lcgn with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def init_tower_batch(self, towerI, towersNum, dataSize):
        towerBatchSize = tf.floordiv(dataSize, towersNum)
        start = towerI * towerBatchSize
        end = (towerI+1)*towerBatchSize if towerI < towersNum-1 else dataSize

        self.questionIndices = self.questionIndicesAll[start:end]
        self.questionLengths = self.questionLengthsAll[start:end]
        self.images = self.imagesAll[start:end]
        self.imagesObjectNum = self.imagesObjectNumAll[start:end]
        self.answerIndices = self.answerIndicesAll[start:end]
        self.batchSize = end - start 
Example #21
Source File: seq2seq_helpers.py    From DeepDeepParser with Apache License 2.0 5 votes vote down vote up
def gather_forced_att_logits(encoder_input_symbols, encoder_decoder_vocab_map, 
                             att_logit, batch_size, attn_length, 
                             target_vocab_size):
  """Gathers attention weights as logits for forced attention."""
  flat_input_symbols = tf.reshape(encoder_input_symbols, [-1])
  flat_label_symbols = tf.gather(encoder_decoder_vocab_map,
      flat_input_symbols)
  flat_att_logits = tf.reshape(att_logit, [-1])

  flat_range = tf.to_int64(tf.range(tf.shape(flat_label_symbols)[0]))
  batch_inds = tf.floordiv(flat_range, attn_length)
  position_inds = tf.mod(flat_range, attn_length)
  attn_vocab_inds = tf.transpose(tf.pack(
      [batch_inds, position_inds, tf.to_int64(flat_label_symbols)]))
 
  # Exclude indexes of entries with flat_label_symbols[i] = -1.
  included_flat_indexes = tf.reshape(tf.where(tf.not_equal(
      flat_label_symbols, -1)), [-1])
  included_attn_vocab_inds = tf.gather(attn_vocab_inds, 
      included_flat_indexes)
  included_flat_att_logits = tf.gather(flat_att_logits, 
      included_flat_indexes)

  sparse_shape = tf.to_int64(tf.pack(
      [batch_size, attn_length, target_vocab_size]))

  sparse_label_logits = tf.SparseTensor(included_attn_vocab_inds, 
      included_flat_att_logits, sparse_shape)
  forced_att_logit_sum = tf.sparse_reduce_sum(sparse_label_logits, [1])

  forced_att_logit = tf.reshape(forced_att_logit_sum, 
      [-1, target_vocab_size])

  return forced_att_logit 
Example #22
Source File: det_tools.py    From hfnet with MIT License 5 votes vote down vote up
def extract_xy_coords(d_heatmaps, block_size):
    batch = tf.shape(d_heatmaps)[0]
    rheight = tf.shape(d_heatmaps)[1]
    rwidth = tf.shape(d_heatmaps)[2]
    width = rwidth * block_size
    height = rheight * block_size

    d_argmax = tf.cast(tf.argmax(d_heatmaps, axis=-1), dtype=tf.int32)
    fgmask = tf.cast(tf.not_equal(d_argmax, block_size**2), dtype=tf.int32)

    x_bcoords = tf.mod(d_argmax, block_size)
    y_bcoords = tf.floordiv(d_argmax, block_size) # floor_div ?
    zero = tf.constant(0, dtype=tf.int32)
    zeros = tf.zeros_like(x_bcoords)

    x_bcoords = tf.where(tf.equal(fgmask, zero), zeros, x_bcoords)
    y_bcoords = tf.where(tf.equal(fgmask, zero), zeros, y_bcoords)

    x_offset, y_offset = tf.meshgrid(tf.range(0, width, block_size), tf.range(0, height, block_size))
    x_offset = tf.tile(tf.expand_dims(x_offset, axis=0), [batch, 1, 1])
    y_offset = tf.tile(tf.expand_dims(y_offset, axis=0), [batch, 1, 1])

    x_icoords = x_bcoords + x_offset
    y_icoords = y_bcoords + y_offset

    return x_icoords, y_icoords, fgmask 
Example #23
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testOverload(self):
    dtypes = [
        tf.float16,
        tf.float32,
        tf.float64,
        tf.int32,
        tf.int64,
        tf.complex64,
        tf.complex128,
    ]
    funcs = [
        (np.add, _ADD),
        (np.subtract, _SUB),
        (np.multiply, _MUL),
        (np.power, _POW),
        (np.true_divide, _TRUEDIV),
        (np.floor_divide, _FLOORDIV),
    ]
    for dtype in dtypes:
      for np_func, tf_func in funcs:
        if dtype in (tf.complex64, tf.complex128) and tf_func == _FLOORDIV:
          continue  # floordiv makes no sense for complex
        self._compareBinary(10, 5, dtype, np_func, tf_func)
    # Mod only works for int32 and int64.
    for dtype in [tf.int32, tf.int64]:
      self._compareBinary(10, 3, dtype, np.mod, _MOD) 
Example #24
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def _testBCastD(self, xs, ys):
    funcs = [
        (np.true_divide, tf.truediv),
        (np.floor_divide, tf.floordiv),
        (np.true_divide, _TRUEDIV),
        (np.floor_divide, _FLOORDIV),
    ]
    self._testBCastByFunc(funcs, xs, ys) 
Example #25
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testUint16Basic(self):
    x = np.arange(1, 13, 2).reshape(1, 3, 2).astype(np.uint16)
    y = np.arange(1, 7, 1).reshape(1, 3, 2).astype(np.uint16)
    self._compareBoth(x, y, np.multiply, tf.mul)
    self._compareBoth(x, y, np.multiply, _MUL)
    self._compareBoth(x, y, np.true_divide, tf.truediv)
    self._compareBoth(x, y, np.floor_divide, tf.floordiv)
    self._compareBoth(x, y, np.true_divide, _TRUEDIV)
    self._compareBoth(x, y, np.floor_divide, _FLOORDIV) 
Example #26
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def _compareBoth(self, x, y, np_func, tf_func, also_compare_variables=False):
    self._compareCpu(x, y, np_func, tf_func, also_compare_variables)
    if x.dtype in (np.float16, np.float32, np.float64):
      if tf_func not in (_FLOORDIV, tf.floordiv, tf.igamma, tf.igammac, tf.zeta, tf.polygamma):
        self._compareGradientX(x, y, np_func, tf_func)
        self._compareGradientY(x, y, np_func, tf_func)
      if tf_func in (tf.igamma, tf.igammac, tf.zeta, tf.polygamma):
        # These methods only support gradients in the second parameter
        self._compareGradientY(x, y, np_func, tf_func)
      self._compareGpu(x, y, np_func, tf_func) 
Example #27
Source File: swa_train_cpn.py    From tf.fashionAI with Apache License 2.0 5 votes vote down vote up
def get_keypoint(image, targets, predictions, heatmap_size, height, width, category, clip_at_zero=True, data_format='channels_last', name=None):
    predictions = tf.reshape(predictions, [1, -1, heatmap_size*heatmap_size])

    pred_max = tf.reduce_max(predictions, axis=-1)
    pred_indices = tf.argmax(predictions, axis=-1)
    pred_x, pred_y = tf.cast(tf.floormod(pred_indices, heatmap_size), tf.float32), tf.cast(tf.floordiv(pred_indices, heatmap_size), tf.float32)

    width, height = tf.cast(width, tf.float32), tf.cast(height, tf.float32)
    pred_x, pred_y = pred_x * width / tf.cast(heatmap_size, tf.float32), pred_y * height / tf.cast(heatmap_size, tf.float32)

    if clip_at_zero:
      pred_x, pred_y =  pred_x * tf.cast(pred_max>0, tf.float32), pred_y * tf.cast(pred_max>0, tf.float32)
      pred_x = pred_x * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (width / 2.)
      pred_y = pred_y * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (height / 2.)

    if config.PRED_DEBUG:
      pred_indices_ = tf.squeeze(pred_indices)
      image_ = tf.squeeze(image) * 255.
      pred_heatmap = tf.one_hot(pred_indices_, heatmap_size*heatmap_size, on_value=1., off_value=0., axis=-1, dtype=tf.float32)

      pred_heatmap = tf.reshape(pred_heatmap, [-1, heatmap_size, heatmap_size])
      if data_format == 'channels_first':
        image_ = tf.transpose(image_, perm=(1, 2, 0))
      save_image_op = tf.py_func(save_image_with_heatmap,
                                  [image_, height, width,
                                  heatmap_size,
                                  tf.reshape(pred_heatmap * 255., [-1, heatmap_size, heatmap_size]),
                                  tf.reshape(predictions, [-1, heatmap_size, heatmap_size]),
                                  config.left_right_group_map[category][0],
                                  config.left_right_group_map[category][1],
                                  config.left_right_group_map[category][2]],
                                  tf.int64, stateful=True)
      with tf.control_dependencies([save_image_op]):
        pred_x, pred_y = pred_x * 1., pred_y * 1.
    return pred_x, pred_y 
Example #28
Source File: keras_contrib_backend.py    From se_relativisticgan with MIT License 5 votes vote down vote up
def extract_image_patches(x, ksizes, ssizes, padding='same',
                          data_format='channels_last'):
    '''
    Extract the patches from an image
    # Parameters
        x : The input image
        ksizes : 2-d tuple with the kernel size
        ssizes : 2-d tuple with the strides size
        padding : 'same' or 'valid'
        data_format : 'channels_last' or 'channels_first'
    # Returns
        The (k_w,k_h) patches extracted
        TF ==> (batch_size,w,h,k_w,k_h,c)
        TH ==> (batch_size,w,h,c,k_w,k_h)
    '''
    kernel = [1, ksizes[0], ksizes[1], 1]
    strides = [1, ssizes[0], ssizes[1], 1]
    padding = _preprocess_padding(padding)
    if data_format == 'channels_first':
        x = KTF.permute_dimensions(x, (0, 2, 3, 1))
    bs_i, w_i, h_i, ch_i = KTF.int_shape(x)
    patches = tf.extract_image_patches(x, kernel, strides, [1, 1, 1, 1],
                                       padding)
    # Reshaping to fit Theano
    bs, w, h, ch = KTF.int_shape(patches)
    patches = tf.reshape(tf.transpose(tf.reshape(patches, [-1, w, h, tf.floordiv(ch, ch_i), ch_i]), [0, 1, 2, 4, 3]),
                         [-1, w, h, ch_i, ksizes[0], ksizes[1]])
    if data_format == 'channels_last':
        patches = KTF.permute_dimensions(patches, [0, 1, 2, 4, 5, 3])
    return patches 
Example #29
Source File: preprocessing.py    From finetune_classification with Apache License 2.0 5 votes vote down vote up
def _border_expand(image, mode='CONSTANT', constant_values=255):
    """Expands the given image.
    
    Args:
        Args:
        image: A 3-D image `Tensor`.
        output_height: The height of the image after Expanding.
        output_width: The width of the image after Expanding.
        resize: A boolean indicating whether to resize the expanded image
            to [output_height, output_width, channels] or not.

    Returns:
        expanded_image: A 3-D tensor containing the resized image.
    """
    shape = tf.shape(image)
    height = shape[0]
    width = shape[1]
    
    def _pad_left_right():
        pad_left = tf.floordiv(height - width, 2)
        pad_right = height - width - pad_left
        return [[0, 0], [pad_left, pad_right], [0, 0]]
        
    def _pad_top_bottom():
        pad_top = tf.floordiv(width - height, 2)
        pad_bottom = width - height - pad_top
        return [[pad_top, pad_bottom], [0, 0], [0, 0]]
    
    paddings = tf.cond(tf.greater(height, width),
                       _pad_left_right,
                       _pad_top_bottom)
    expanded_image = tf.pad(image, paddings, mode=mode, 
                          constant_values=constant_values)
    return expanded_image 
Example #30
Source File: ops.py    From tfdeploy with MIT License 5 votes vote down vote up
def test_FloorDiv(self):
        t = tf.floordiv(*self.random((3, 5), (3, 5)))
        self.check(t)