当前位置: 首页>>代码示例>>Python>>正文


Python tensorflow.py_func方法代码示例

本文整理汇总了Python中tensorflow.py_func方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.py_func方法的具体用法?Python tensorflow.py_func怎么用?Python tensorflow.py_func使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tensorflow的用法示例。


在下文中一共展示了tensorflow.py_func方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_noise

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def add_noise(ids, sequence_length):
  """Wraps add_noise_python for a batch of tensors."""

  def _add_noise_single(ids, sequence_length):
    noisy_ids = add_noise_python(ids[:sequence_length])
    noisy_sequence_length = len(noisy_ids)
    ids[:noisy_sequence_length] = noisy_ids
    ids[noisy_sequence_length:] = 0
    return ids, np.int32(noisy_sequence_length)

  noisy_ids, noisy_sequence_length = tf.map_fn(
      lambda x: tf.py_func(_add_noise_single, x, [ids.dtype, tf.int32]),
      [ids, sequence_length],
      dtype=[ids.dtype, tf.int32],
      back_prop=False)

  noisy_ids.set_shape(ids.get_shape())
  noisy_sequence_length.set_shape(sequence_length.get_shape())

  return noisy_ids, noisy_sequence_length


# Step 3 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:25,代码来源:train.py

示例2: _py_func_with_gradient

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
                           grad_func=None):
    """
    PyFunc defined as given by Tensorflow
    :param func: Custom Function
    :param inp: Function Inputs
    :param Tout: Ouput Type of out Custom Function
    :param stateful: Calculate Gradients when stateful is True
    :param name: Name of the PyFunction
    :param grad: Custom Gradient Function
    :return:
    """
    # Generate random name in order to avoid conflicts with inbuilt names
    rnd_name = 'PyFuncGrad-' + '%0x' % getrandbits(30 * 4)

    # Register Tensorflow Gradient
    tf.RegisterGradient(rnd_name)(grad_func)

    # Get current graph
    g = tf.get_default_graph()

    # Add gradient override map
    with g.gradient_override_map(
            {"PyFunc": rnd_name, "PyFuncStateless": rnd_name}):
        return tf.py_func(func, inp, Tout, stateful=stateful, name=name) 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:27,代码来源:utils_pytorch.py

示例3: simulate

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def simulate(self, action):
    """Step the batch of environments.

    The results of the step can be accessed from the variables defined below.

    Args:
      action: Tensor holding the batch of actions to apply.

    Returns:
      Operation.
    """
    with tf.name_scope('environment/simulate'):
      if action.dtype in (tf.float16, tf.float32, tf.float64):
        action = tf.check_numerics(action, 'action')
      observ_dtype = self._parse_dtype(self._batch_env.observation_space)
      observ, reward, done = tf.py_func(
          lambda a: self._batch_env.step(a)[:3], [action],
          [observ_dtype, tf.float32, tf.bool], name='step')
      observ = tf.check_numerics(observ, 'observ')
      reward = tf.check_numerics(reward, 'reward')
      return tf.group(
          self._observ.assign(observ),
          self._action.assign(action),
          self._reward.assign(reward),
          self._done.assign(done)) 
开发者ID:utra-robosoccer,项目名称:soccer-matlab,代码行数:27,代码来源:in_graph_batch_env.py

示例4: reset

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def reset(self, indices=None):
    """Reset the batch of environments.

    Args:
      indices: The batch indices of the environments to reset; defaults to all.

    Returns:
      Batch tensor of the new observations.
    """
    if indices is None:
      indices = tf.range(len(self._batch_env))
    observ_dtype = self._parse_dtype(self._batch_env.observation_space)
    observ = tf.py_func(
        self._batch_env.reset, [indices], observ_dtype, name='reset')
    observ = tf.check_numerics(observ, 'observ')
    reward = tf.zeros_like(indices, tf.float32)
    done = tf.zeros_like(indices, tf.bool)
    with tf.control_dependencies([
        tf.scatter_update(self._observ, indices, observ),
        tf.scatter_update(self._reward, indices, reward),
        tf.scatter_update(self._done, indices, done)]):
      return tf.identity(observ) 
开发者ID:utra-robosoccer,项目名称:soccer-matlab,代码行数:24,代码来源:in_graph_batch_env.py

示例5: simulate

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def simulate(self, action):
    """Step the batch of environments.

    The results of the step can be accessed from the variables defined below.

    Args:
      action: Tensor holding the batch of actions to apply.

    Returns:
      Operation.
    """
    with tf.name_scope('environment/simulate'):
      if action.dtype in (tf.float16, tf.float32, tf.float64):
        action = tf.check_numerics(action, 'action')
      observ_dtype = utils.parse_dtype(self._batch_env.observation_space)
      observ, reward, done = tf.py_func(
          lambda a: self._batch_env.step(a)[:3], [action],
          [observ_dtype, tf.float32, tf.bool], name='step')
      observ = tf.check_numerics(observ, 'observ')
      reward = tf.check_numerics(reward, 'reward')
      reward.set_shape((len(self),))
      done.set_shape((len(self),))
      with tf.control_dependencies([self._observ.assign(observ)]):
        return tf.identity(reward), tf.identity(done) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:26,代码来源:py_func_batch_env.py

示例6: _reset_non_empty

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def _reset_non_empty(self, indices):
    """Reset the batch of environments.

    Args:
      indices: The batch indices of the environments to reset; defaults to all.

    Returns:
      Batch tensor of the new observations.
    """
    observ_dtype = utils.parse_dtype(self._batch_env.observation_space)
    observ = tf.py_func(
        self._batch_env.reset, [indices], observ_dtype, name='reset')
    observ = tf.check_numerics(observ, 'observ')
    with tf.control_dependencies([
        tf.scatter_update(self._observ, indices, observ)]):
      return tf.identity(observ) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:18,代码来源:py_func_batch_env.py

示例7: rouge_l_fscore

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def rouge_l_fscore(predictions, labels, **unused_kwargs):
  """ROUGE scores computation between labels and predictions.

  This is an approximate ROUGE scoring method since we do not glue word pieces
  or decode the ids and tokenize the output.

  Args:
    predictions: tensor, model predictions
    labels: tensor, gold output.

  Returns:
    rouge_l_fscore: approx rouge-l f1 score.
  """
  outputs = tf.to_int32(tf.argmax(predictions, axis=-1))
  # Convert the outputs and labels to a [batch_size, input_length] tensor.
  outputs = tf.squeeze(outputs, axis=[-1, -2])
  labels = tf.squeeze(labels, axis=[-1, -2])
  rouge_l_f_score = tf.py_func(rouge_l_sentence_level, (outputs, labels),
                               tf.float32)
  return rouge_l_f_score, tf.constant(1.0) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:22,代码来源:rouge.py

示例8: rouge_2_fscore

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def rouge_2_fscore(predictions, labels, **unused_kwargs):
  """ROUGE-2 F1 score computation between labels and predictions.

  This is an approximate ROUGE scoring method since we do not glue word pieces
  or decode the ids and tokenize the output.

  Args:
    predictions: tensor, model predictions
    labels: tensor, gold output.

  Returns:
    rouge2_fscore: approx rouge-2 f1 score.
  """

  outputs = tf.to_int32(tf.argmax(predictions, axis=-1))
  # Convert the outputs and labels to a [batch_size, input_length] tensor.
  outputs = tf.squeeze(outputs, axis=[-1, -2])
  labels = tf.squeeze(labels, axis=[-1, -2])
  rouge_2_f_score = tf.py_func(rouge_n, (outputs, labels), tf.float32)
  return rouge_2_f_score, tf.constant(1.0) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:22,代码来源:rouge.py

示例9: bleu_score

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def bleu_score(predictions, labels, **unused_kwargs):
  """BLEU score computation between labels and predictions.

  An approximate BLEU scoring method since we do not glue word pieces or
  decode the ids and tokenize the output. By default, we use ngram order of 4
  and use brevity penalty. Also, this does not have beam search.

  Args:
    predictions: tensor, model predictions
    labels: tensor, gold output.

  Returns:
    bleu: int, approx bleu score
  """
  outputs = tf.to_int32(tf.argmax(predictions, axis=-1))
  # Convert the outputs and labels to a [batch_size, input_length] tensor.
  outputs = tf.squeeze(outputs, axis=[-1, -2])
  labels = tf.squeeze(labels, axis=[-1, -2])

  bleu = tf.py_func(compute_bleu, (labels, outputs), tf.float32)
  return bleu, tf.constant(1.0) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:23,代码来源:bleu_hook.py

示例10: compute_gradients

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def compute_gradients(self, loss, var_list, **kwargs):
        grads_and_vars = tf.train.AdamOptimizer.compute_gradients(self, loss, var_list, **kwargs)
        grads_and_vars = [(g, v) for g, v in grads_and_vars if g is not None]
        flat_grad = tf.concat([tf.reshape(g, (-1,)) for g, v in grads_and_vars], axis=0)
        shapes = [v.shape.as_list() for g, v in grads_and_vars]
        sizes = [int(np.prod(s)) for s in shapes]

        num_tasks = self.comm.Get_size()
        buf = np.zeros(sum(sizes), np.float32)

        def _collect_grads(flat_grad):
            self.comm.Allreduce(flat_grad, buf, op=MPI.SUM)
            np.divide(buf, float(num_tasks), out=buf)
            return buf

        avg_flat_grad = tf.py_func(_collect_grads, [flat_grad], tf.float32)
        avg_flat_grad.set_shape(flat_grad.shape)
        avg_grads = tf.split(avg_flat_grad, sizes, axis=0)
        avg_grads_and_vars = [(tf.reshape(g, v.shape), v)
                    for g, (_, v) in zip(avg_grads, grads_and_vars)]

        return avg_grads_and_vars 
开发者ID:MaxSobolMark,项目名称:HardRLWithYoutube,代码行数:24,代码来源:mpi_adam_optimizer.py

示例11: tf_msssim_np

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def tf_msssim_np(img1, img2, data_format='NHWC'):
    assert img1.shape.ndims == img2.shape.ndims == 4, 'Expected {}, got {}'.format(data_format, img1.shape, img2.shape)
    assert tf.uint8.is_compatible_with(img1.dtype), 'Expected uint8 intput'
    assert tf.uint8.is_compatible_with(img2.dtype), 'Expected uint8 intput'

    if data_format == 'NCHW':
        def make_NHWC(x):
            return tf.transpose(x, (0, 2, 3, 1), name='make_NHWC')
        return tf_msssim_np(make_NHWC(img1), make_NHWC(img2), data_format='NHWC')

    assert img1.shape[3] == 3, 'Expected 3-channel images, got {}'.format(img1)

    with tf.name_scope('ms-ssim_np'):
        v = tf.py_func(_calc_msssim_orig, [img1, img2], tf.float32, stateful=False, name='MS-SSIM')
        v.set_shape(())
        return v 
开发者ID:fab-jul,项目名称:imgcomp-cvpr,代码行数:18,代码来源:ms_ssim_np.py

示例12: anchor_target_layer

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def anchor_target_layer(cls_pred, bbox, im_info, scope_name):
    with tf.variable_scope(scope_name) as scope:
        # 'rpn_cls_score', 'gt_boxes', 'im_info'
        rpn_labels, rpn_bbox_targets, rpn_bbox_inside_weights, rpn_bbox_outside_weights = \
            tf.py_func(anchor_target_layer_py,
                       [cls_pred, bbox, im_info, [16, ], [16]],
                       [tf.float32, tf.float32, tf.float32, tf.float32])

        rpn_labels = tf.convert_to_tensor(tf.cast(rpn_labels, tf.int32),
                                          name='rpn_labels')
        rpn_bbox_targets = tf.convert_to_tensor(rpn_bbox_targets,
                                                name='rpn_bbox_targets')
        rpn_bbox_inside_weights = tf.convert_to_tensor(rpn_bbox_inside_weights,
                                                       name='rpn_bbox_inside_weights')
        rpn_bbox_outside_weights = tf.convert_to_tensor(rpn_bbox_outside_weights,
                                                        name='rpn_bbox_outside_weights')

        return [rpn_labels, rpn_bbox_targets, rpn_bbox_inside_weights, rpn_bbox_outside_weights] 
开发者ID:zzzDavid,项目名称:ICDAR-2019-SROIE,代码行数:20,代码来源:model_train.py

示例13: rouge_l_fscore

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def rouge_l_fscore(hypothesis, references, **unused_kwargs):
  """ROUGE scores computation between labels and predictions.

  This is an approximate ROUGE scoring method since we do not glue word pieces
  or decode the ids and tokenize the output.

  Args:
    predictions: tensor, model predictions (batch_size, <=max_dec_steps)
    labels: tensor, gold output. (batch_size, max_dec_steps)

  Returns:
    rouge_l_fscore: approx rouge-l f1 score.
  """
  rouge_l_f_score = tf.py_func(rouge_l_sentence_level, (hypothesis, references), [tf.float32])
  #rouge_l_f_score = tf.py_func(rouge_l_sentence_level, (hypothesis, references), tf.float32)
  return rouge_l_f_score 
开发者ID:yaserkl,项目名称:TransferRL,代码行数:18,代码来源:rouge_tensor.py

示例14: rouge_2_fscore

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def rouge_2_fscore(predictions, labels, **unused_kwargs):
  """ROUGE-2 F1 score computation between labels and predictions.

  This is an approximate ROUGE scoring method since we do not glue word pieces
  or decode the ids and tokenize the output.

  Args:
    predictions: tensor, model predictions (batch_size, <=max_dec_steps)
    labels: tensor, gold output. (batch_size, max_dec_steps)

  Returns:
    rouge2_fscore: approx rouge-2 f1 score.
  """

  rouge_2_f_score = tf.py_func(rouge_n, (predictions, labels), [tf.float32])
  return rouge_2_f_score, tf.constant(1.0) 
开发者ID:yaserkl,项目名称:TransferRL,代码行数:18,代码来源:rouge_tensor.py

示例15: generate_gt_graph

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import py_func [as 别名]
def generate_gt_graph(gt_quadrilaterals, input_gt_class_ids, image_shape, width_stride, max_gt_num):
    """

    :param gt_quadrilaterals: [mat_gt_num,(x1,y1,x2,y2,x3,y3,x4,y4,tag)] 左上、右上、右下、左下(顺时针)
    :param input_gt_class_ids:
    :param image_shape:
    :param width_stride:
    :param max_gt_num:
    :return:
    """

    gt_quadrilaterals = tf_utils.remove_pad(gt_quadrilaterals)
    input_gt_class_ids = tf_utils.remove_pad(input_gt_class_ids)
    gt_boxes, gt_class_ids = tf.py_func(func=gt_utils.gen_gt_from_quadrilaterals,
                          inp=[gt_quadrilaterals, input_gt_class_ids, image_shape, width_stride],
                          Tout=[tf.float32] * 2)
    return tf_utils.pad_list_to_fixed_size([gt_boxes, gt_class_ids], max_gt_num) 
开发者ID:yizt,项目名称:keras-ctpn,代码行数:19,代码来源:gt.py


注:本文中的tensorflow.py_func方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。