當前位置: 首頁>>代碼示例>>Python>>正文


Python v1.logical_and方法代碼示例

本文整理匯總了Python中tensorflow.compat.v1.logical_and方法的典型用法代碼示例。如果您正苦於以下問題:Python v1.logical_and方法的具體用法?Python v1.logical_and怎麽用?Python v1.logical_and使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在tensorflow.compat.v1的用法示例。


在下文中一共展示了v1.logical_and方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: unwrap

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def unwrap(p, discont=np.pi, axis=-1):
  """Unwrap a cyclical phase tensor.

  Args:
    p: Phase tensor.
    discont: Float, size of the cyclic discontinuity.
    axis: Axis of which to unwrap.

  Returns:
    unwrapped: Unwrapped tensor of same size as input.
  """
  dd = diff(p, axis=axis)
  ddmod = tf.mod(dd + np.pi, 2.0 * np.pi) - np.pi
  idx = tf.logical_and(tf.equal(ddmod, -np.pi), tf.greater(dd, 0))
  ddmod = tf.where(idx, tf.ones_like(ddmod) * np.pi, ddmod)
  ph_correct = ddmod - dd
  idx = tf.less(tf.abs(dd), discont)
  ddmod = tf.where(idx, tf.zeros_like(ddmod), dd)
  ph_cumsum = tf.cumsum(ph_correct, axis=axis)

  shape = p.get_shape().as_list()
  shape[axis] = 1
  ph_cumsum = tf.concat([tf.zeros(shape, dtype=p.dtype), ph_cumsum], axis=axis)
  unwrapped = p + ph_cumsum
  return unwrapped 
開發者ID:magenta,項目名稱:magenta,代碼行數:27,代碼來源:spectral_ops.py

示例2: _build

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def _build(self, inputs, labels):

    def cond(i, unused_attack, success):
      # If we are already successful, we break.
      return tf.logical_and(i < self._num_restarts,
                            tf.logical_not(tf.reduce_all(success)))

    def body(i, attack, success):
      new_attack = self._inner_attack(inputs, labels)
      new_success = self._inner_attack.success
      # The first iteration always sets the attack.
      use_new_values = tf.logical_or(tf.equal(i, 0), new_success)
      return (i + 1,
              tf.where(use_new_values, new_attack, attack),
              tf.logical_or(success, new_success))

    _, self._attack, self._success = tf.while_loop(
        cond, body, back_prop=False, parallel_iterations=1,
        loop_vars=[
            tf.constant(0, dtype=tf.int32),
            inputs,
            tf.zeros([tf.shape(inputs)[0]], dtype=tf.bool),
        ])
    self._logits = self._eval_fn(self._attack, mode='final')
    return self._attack 
開發者ID:deepmind,項目名稱:interval-bound-propagation,代碼行數:27,代碼來源:attacks.py

示例3: compare_generating_steps

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def compare_generating_steps(target_decode_steps, predicted_decode_steps):
  """Compare generating steps only but ignoring target copying steps.

  Args:
    target_decode_steps: Target DecodeSteps, Each tensor is expected to be shape
      [batch_size, output_length].
    predicted_decode_steps: Predicted DecodeSteps, Each tensor is expected to be
      shape [batch_size, output_length].

  Returns:
    A tensor of bools indicating whether generating steps are equal.
    Copy Steps will have value True.
  """
  # Set all copying steps to True, Since we only care about generating steps.
  return tf.logical_or(
      tf.not_equal(target_decode_steps.action_types, constants.GENERATE_ACTION),
      tf.logical_and(
          tf.equal(target_decode_steps.action_types,
                   predicted_decode_steps.action_types),
          tf.equal(target_decode_steps.action_ids,
                   predicted_decode_steps.action_ids))) 
開發者ID:google-research,項目名稱:language,代碼行數:23,代碼來源:decode_utils.py

示例4: mask_attention

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def mask_attention(attention, seq_len1, seq_len2):
  """Masks an attention matrix.

  Args:
    attention: <tf.float32>[batch, seq_len1, seq_len2]
    seq_len1: <tf.int32>[batch]
    seq_len2: <tf.int32>[batch]

  Returns:
    the masked scores <tf.float32>[batch, seq_len1, seq_len2]
  """
  dim1 = tensor_utils.shape(attention, 1)
  dim2 = tensor_utils.shape(attention, 2)
  m1 = tf.sequence_mask(seq_len1, dim1)
  m2 = tf.sequence_mask(seq_len2, dim2)
  joint_mask = tf.logical_and(tf.expand_dims(m1, 2), tf.expand_dims(m2, 1))
  return ops.mask_logits(attention, joint_mask) 
開發者ID:google-research,項目名稱:language,代碼行數:19,代碼來源:run_recurrent_model_boolq.py

示例5: noise_span_to_sentinel

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def noise_span_to_sentinel(tokens, noise_mask, vocabulary):
  """Replace each run of consecutive noise tokens with a single sentinel.

  Args:
    tokens: a 1d integer Tensor
    noise_mask: a boolean Tensor with the same shape as tokens
    vocabulary: a vocabulary.Vocabulary
  Returns:
    a Tensor with the same shape and dtype as tokens
  """
  tokens = tf.where_v2(noise_mask,
                       tf.cast(sentinel_id(vocabulary), tokens.dtype),
                       tokens)
  prev_token_is_noise = tf.pad(noise_mask[:-1], [[1, 0]])
  subsequent_noise_tokens = tf.logical_and(noise_mask, prev_token_is_noise)
  return tf.boolean_mask(tokens, tf.logical_not(subsequent_noise_tokens)) 
開發者ID:google-research,項目名稱:text-to-text-transfer-transformer,代碼行數:18,代碼來源:preprocessors.py

示例6: prune_small_boxes

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def prune_small_boxes(boxlist, min_side, scope=None):
  """Prunes small boxes in the boxlist which have a side smaller than min_side.

  Args:
    boxlist: BoxList holding N boxes.
    min_side: Minimum width AND height of box to survive pruning.
    scope: name scope.

  Returns:
    A pruned boxlist.
  """
  with tf.name_scope(scope, 'PruneSmallBoxes'):
    height, width = height_width(boxlist)
    is_valid = tf.logical_and(tf.greater_equal(width, min_side),
                              tf.greater_equal(height, min_side))
    return gather(boxlist, tf.reshape(tf.where(is_valid), [-1])) 
開發者ID:tensorflow,項目名稱:models,代碼行數:18,代碼來源:box_list_ops.py

示例7: example_valid_size

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def example_valid_size(example, min_length, max_length):
  length = example_length(example)
  return tf.logical_and(
      length >= min_length,
      length <= max_length,
  ) 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:8,代碼來源:data_reader.py

示例8: weights_concatenated

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def weights_concatenated(labels):
  """Assign weight 1.0 to the "target" part of the concatenated labels.

  The labels look like:
    source English I love you . ID1 target French Je t'aime . ID1 source
      English the cat ID1 target French le chat ID1 source English ...

  We want to assign weight 1.0 to all words in the target text (including the
  ID1 end symbol), but not to the source text or the boilerplate.  In the
  above example, the target words that get positive weight are:
    Je t'aime . ID1 le chat ID1

  Args:
    labels: a Tensor
  Returns:
    a Tensor
  """
  eos_mask = tf.to_int32(tf.equal(labels, 1))
  sentence_num = tf.cumsum(eos_mask, axis=1, exclusive=True)
  in_target = tf.equal(tf.mod(sentence_num, 2), 1)
  # first two tokens of each sentence are boilerplate.
  sentence_num_plus_one = sentence_num + 1
  shifted = tf.pad(sentence_num_plus_one,
                   [[0, 0], [2, 0], [0, 0], [0, 0]])[:, :-2, :, :]
  nonboilerplate = tf.equal(sentence_num_plus_one, shifted)
  ret = to_float(tf.logical_and(nonboilerplate, in_target))
  return ret 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:29,代碼來源:common_layers.py

示例9: _crop

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def _crop(image, offset_height, offset_width, crop_height, crop_width):
  """Crops the given image using the provided offsets and sizes.

  Note that the method doesn't assume we know the input image size but it does
  assume we know the input image rank.

  Args:
    image: `Tensor` image of shape [height, width, channels].
    offset_height: `Tensor` indicating the height offset.
    offset_width: `Tensor` indicating the width offset.
    crop_height: the height of the cropped image.
    crop_width: the width of the cropped image.

  Returns:
    the cropped (and resized) image.

  Raises:
    InvalidArgumentError: if the rank is not 3 or if the image dimensions are
      less than the crop size.
  """
  original_shape = tf.shape(image)

  rank_assertion = tf.Assert(
      tf.equal(tf.rank(image), 3), ["Rank of image must be equal to 3."])
  with tf.control_dependencies([rank_assertion]):
    cropped_shape = tf.stack([crop_height, crop_width, original_shape[2]])

  size_assertion = tf.Assert(
      tf.logical_and(
          tf.greater_equal(original_shape[0], crop_height),
          tf.greater_equal(original_shape[1], crop_width)),
      ["Crop size greater than the image size."])

  offsets = tf.to_int32(tf.stack([offset_height, offset_width, 0]))

  # Use tf.slice instead of crop_to_bounding box as it accepts tensors to
  # define the crop size.
  with tf.control_dependencies([size_assertion]):
    image = tf.slice(image, offsets, cropped_shape)
  return tf.reshape(image, cropped_shape) 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:42,代碼來源:imagenet.py

示例10: apply_increasing_monotonic_fn

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def apply_increasing_monotonic_fn(self, wrapper, fn, *args, **parameters):
    if fn.__name__ != 'relu':
      # Fallback to regular interval bound propagation for unsupported
      # operations.
      logging.warn('"%s" is not supported by SymbolicBounds. '
                   'Fallback on IntervalBounds.', fn.__name__)
      interval_bounds = basic_bounds.IntervalBounds.convert(self)
      converted_args = [basic_bounds.IntervalBounds.convert(b) for b in args]
      interval_bounds = interval_bounds._increasing_monotonic_fn(  # pylint: disable=protected-access
          fn, *converted_args)
      return self.convert(interval_bounds)

    concrete = self.concretize()
    lb, ub = concrete.lower, concrete.upper
    is_ambiguous = tf.logical_and(ub > 0, lb < 0)
    # Ensure denominator is always positive, even when not needed.
    ambiguous_denom = tf.where(is_ambiguous, ub - lb, tf.ones_like(ub))
    scale = tf.where(
        is_ambiguous, ub / ambiguous_denom,
        tf.where(lb >= 0, tf.ones_like(lb), tf.zeros_like(lb)))
    bias = tf.where(is_ambiguous, -lb, tf.zeros_like(lb))
    lb_out = LinearExpression(
        w=tf.expand_dims(scale, 1) * self.lower.w,
        b=scale * self.lower.b,
        lower=self.lower.lower, upper=self.lower.upper)
    ub_out = LinearExpression(
        w=tf.expand_dims(scale, 1) * self.upper.w,
        b=scale * (self.upper.b + bias),
        lower=self.upper.lower, upper=self.upper.upper)
    return SymbolicBounds(lb_out, ub_out).with_priors(wrapper.output_bounds) 
開發者ID:deepmind,項目名稱:interval-bound-propagation,代碼行數:32,代碼來源:fastlin.py

示例11: maybe_flip

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def maybe_flip(image, label, flip_axis, flip_indicator=None):
  """Randomly flip the image."""
  if flip_indicator is None:
    flip_indicator = tf.random_uniform(shape=[])
  flip_or_not = tf.greater(flip_indicator, 0.5)

  def _maybe_flip(data):
    """Flip or not according to flip_or_not."""
    data = tf.cond(tf.logical_and(flip_or_not, tf.equal(flip_axis, 1)),
                   lambda: tf.transpose(data, [1, 0, 2]),
                   lambda: data)
    data = tf.cond(tf.logical_and(flip_or_not, tf.equal(flip_axis, 2)),
                   lambda: tf.transpose(data, [2, 1, 0]),
                   lambda: data)

    data = tf.cond(flip_or_not,
                   lambda: tf.image.flip_up_down(data),
                   lambda: data)

    data = tf.cond(tf.logical_and(flip_or_not, tf.equal(flip_axis, 1)),
                   lambda: tf.transpose(data, [1, 0, 2]),
                   lambda: data)
    data = tf.cond(tf.logical_and(flip_or_not, tf.equal(flip_axis, 2)),
                   lambda: tf.transpose(data, [2, 1, 0]),
                   lambda: data)
    return data

  return _maybe_flip(image), _maybe_flip(label) 
開發者ID:tensorflow,項目名稱:mesh,代碼行數:30,代碼來源:data_aug_lib.py

示例12: maybe_rot180

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def maybe_rot180(image, label, static_axis, rot180_k=None):
  """Randomly rotate the image 180 degrees."""
  if rot180_k is None:
    rot180_k = 2 * tf.random_uniform(
        shape=[], minval=0, maxval=2, dtype=tf.int32)
  rot_or_not = tf.not_equal(rot180_k, 0)

  def _maybe_rot180(data):
    """Rotate or not according to rot_or_not."""
    data = tf.cond(tf.logical_and(rot_or_not, tf.equal(static_axis, 0)),
                   lambda: tf.transpose(data, [2, 1, 0]),
                   lambda: data)
    data = tf.cond(tf.logical_and(rot_or_not, tf.equal(static_axis, 1)),
                   lambda: tf.transpose(data, [0, 2, 1]),
                   lambda: data)

    data = tf.cond(rot_or_not,
                   lambda: tf.image.rot90(data, k=rot180_k),
                   lambda: data)

    data = tf.cond(tf.logical_and(rot_or_not, tf.equal(static_axis, 0)),
                   lambda: tf.transpose(data, [2, 1, 0]),
                   lambda: data)
    data = tf.cond(tf.logical_and(rot_or_not, tf.equal(static_axis, 1)),
                   lambda: tf.transpose(data, [0, 2, 1]),
                   lambda: data)
    return data

  return _maybe_rot180(image), _maybe_rot180(label) 
開發者ID:tensorflow,項目名稱:mesh,代碼行數:31,代碼來源:data_aug_lib.py

示例13: _get_action_type

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def _get_action_type(extended_indices, output_vocab_size, model_config):
  """Returns action_type tensor."""
  action_type = tf.constant(0, dtype=tf.int64)
  for action_type_range in _get_action_types_to_range(output_vocab_size,
                                                      model_config):
    index_in_range = tf.logical_and(
        tf.greater_equal(extended_indices, action_type_range.start_index),
        tf.less(extended_indices, action_type_range.end_index))
    action_type += (
        tf.to_int64(index_in_range) * tf.constant(
            action_type_range.action_type, dtype=tf.int64))
  return action_type 
開發者ID:google-research,項目名稱:language,代碼行數:14,代碼來源:decode_utils.py

示例14: compute_match_stats

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def compute_match_stats(predictions, labels):
  """Compute statistics that are used to compute evaluation metrics.

  Args:
    predictions: <int32> [batch_size]
    labels: <int32> [batch_size, num_annotators]

  Returns:
    numerator: <float> [batch_size]
    recall_weights: <float> [batch_size]
    precision_weights: <float> [batch_size]
  """
  # <int32> [batch_size, num_labels]
  thresholded_labels = compute_thresholded_labels(labels)
  non_null_mask = tf.greater(thresholded_labels, 0)

  # <bool> [batch_size, num_labels]
  exact_match = tf.equal(tf.expand_dims(predictions, -1), thresholded_labels)
  non_null_match = tf.logical_and(exact_match, non_null_mask)

  # <float> [batch_size]
  non_null_match = tf.to_float(tf.reduce_any(non_null_match, axis=1))
  non_null_gold = tf.to_float(tf.reduce_any(non_null_mask, 1))
  non_null_predictions = tf.to_float(tf.greater(predictions, 0))

  return non_null_match, non_null_gold, non_null_predictions 
開發者ID:google-research,項目名稱:language,代碼行數:28,代碼來源:nq_long_utils.py

示例15: noise_span_to_unique_sentinel

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import logical_and [as 別名]
def noise_span_to_unique_sentinel(tokens, noise_mask, vocabulary):
  """Replace each run of consecutive noise tokens with a different sentinel.

  The idea here is to be able to align the dropped spans in the inputs
  with the markers in the targets.

  We want to generate training examples like
  "We hold X to be Y that" -> "X these truths Y self evident Z"

  Sentinels assigned in decreasing order within the sequence starting at
  vocabulary.size - 1.  That is, we appropriate the last tokens in the
  vocabulary for additional use as sentinels.

  TODO(noam): we may want to try enlarging the vocabulary and leaving room
  for the sentinels instead.  However, this requires enlarging the embedding
  tables in the model, so that is a bigger change.

  Args:
    tokens: a 1d integer Tensor
    noise_mask: a boolean Tensor with the same shape as tokens
    vocabulary: a vocabulary.Vocabulary
  Returns:
    a Tensor with the same shape and dtype as tokens
  """
  vocab_size = vocabulary.vocab_size
  prev_token_is_noise = tf.pad(noise_mask[:-1], [[1, 0]])

  first_noise_tokens = tf.logical_and(
      noise_mask, tf.logical_not(prev_token_is_noise))
  subsequent_noise_tokens = tf.logical_and(noise_mask, prev_token_is_noise)

  sentinel = vocab_size - tf.cumsum(tf.cast(first_noise_tokens, tokens.dtype))

  tokens = tf.where_v2(first_noise_tokens, sentinel, tokens)
  return tf.boolean_mask(tokens, tf.logical_not(subsequent_noise_tokens)) 
開發者ID:google-research,項目名稱:text-to-text-transfer-transformer,代碼行數:37,代碼來源:preprocessors.py


注:本文中的tensorflow.compat.v1.logical_and方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。