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


Python tensorflow.broadcast_to方法代码示例

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


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

示例1: broadcast_iou

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def broadcast_iou(box_1, box_2):
    # box_1: (..., (x1, y1, x2, y2))
    # box_2: (N, (x1, y1, x2, y2))

    # broadcast boxes
    box_1 = tf.expand_dims(box_1, -2)
    box_2 = tf.expand_dims(box_2, 0)
    # new_shape: (..., N, (x1, y1, x2, y2))
    new_shape = tf.broadcast_dynamic_shape(tf.shape(box_1), tf.shape(box_2))
    box_1 = tf.broadcast_to(box_1, new_shape)
    box_2 = tf.broadcast_to(box_2, new_shape)

    int_w = tf.maximum(tf.minimum(box_1[..., 2], box_2[..., 2]) - tf.maximum(box_1[..., 0], box_2[..., 0]), 0)
    int_h = tf.maximum(tf.minimum(box_1[..., 3], box_2[..., 3]) - tf.maximum(box_1[..., 1], box_2[..., 1]), 0)
    int_area = int_w * int_h
    box_1_area = (box_1[..., 2] - box_1[..., 0]) * (box_1[..., 3] - box_1[..., 1])
    box_2_area = (box_2[..., 2] - box_2[..., 0]) * (box_2[..., 3] - box_2[..., 1])
    return int_area / (box_1_area + box_2_area - int_area) 
开发者ID:akkaze,项目名称:tf2-yolo3,代码行数:20,代码来源:utils.py

示例2: test_energy_identity

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def test_energy_identity(self):
    """Checks that energy evaluated between the rest pose and itself is zero."""
    number_vertices = np.random.randint(3, 10)
    batch_size = np.random.randint(3)
    batch_shape = np.random.randint(1, 10, size=(batch_size)).tolist()
    vertices_rest_pose = np.random.uniform(size=(number_vertices, 3))
    vertices_deformed_pose = tf.broadcast_to(
        vertices_rest_pose, shape=batch_shape + [number_vertices, 3])
    quaternions = quaternion.from_euler(
        np.zeros(shape=batch_shape + [number_vertices, 3]))
    num_edges = int(round(number_vertices / 2))
    edges = np.zeros(shape=(num_edges, 2), dtype=np.int32)
    edges[..., 0] = np.linspace(
        0, number_vertices / 2 - 1, num_edges, dtype=np.int32)
    edges[..., 1] = np.linspace(
        number_vertices / 2, number_vertices - 1, num_edges, dtype=np.int32)

    energy = as_conformal_as_possible.energy(
        vertices_rest_pose=vertices_rest_pose,
        vertices_deformed_pose=vertices_deformed_pose,
        quaternions=quaternions,
        edges=edges,
        conformal_energy=False)

    self.assertAllClose(energy, tf.zeros_like(energy)) 
开发者ID:tensorflow,项目名称:graphics,代码行数:27,代码来源:as_conformal_as_possible_test.py

示例3: _broadcast_to_x_shape

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def _broadcast_to_x_shape(x, y):
  """Broadcasts y to same shape as x as needed.

  Args:
    x: An input feature.
    y: A feature that is either the same shape as x or has the same outer
      dimensions as x. If the latter, y is broadcast to the same shape as x.

  Returns:
    A Tensor that contains the broadcasted feature, y.
  """
  # The batch dimension of x and y must be the same, and y must be 1D.
  x_shape = tf.shape(input=x)
  y_shape = tf.shape(input=y)
  assert_eq = tf.compat.v1.assert_equal(x_shape[0], y_shape[0])
  with tf.control_dependencies([assert_eq]):
    y = tf.identity(y)
  rank_delta = tf.rank(x) - tf.rank(y)
  target_shape = tf.concat(
      [tf.shape(y), tf.ones(rank_delta, dtype=tf.int32)], axis=0)
  matched_rank = tf.reshape(y, target_shape)
  return tf.broadcast_to(matched_rank, x_shape) 
开发者ID:tensorflow,项目名称:transform,代码行数:24,代码来源:tf_utils.py

示例4: test_agent_is_checkpointable

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def test_agent_is_checkpointable(self):
    agent = networks.ImpalaDeep(9)
    output0 = _run_actor(agent)

    checkpoint_dir = '/tmp/training_checkpoints'
    checkpoint_prefix = os.path.join(checkpoint_dir, 'model.ckpt')
    ckpt = tf.train.Checkpoint(agent=agent)

    ckpt.save(file_prefix=checkpoint_prefix)

    for v in agent.trainable_variables:
      v.assign_add(tf.broadcast_to(1., v.shape))

    output1 = _run_actor(agent)

    ckpt_path = tf.train.latest_checkpoint(checkpoint_dir)
    ckpt.restore(ckpt_path).assert_consumed()

    output2 = _run_actor(agent)

    self.assertEqual(len(agent.trainable_variables), 39)
    self.assertAllEqual(output0[0].policy_logits, output2[0].policy_logits)
    self.assertNotAllEqual(output0[0].policy_logits, output1[0].policy_logits) 
开发者ID:google-research,项目名称:seed_rl,代码行数:25,代码来源:agents_test.py

示例5: __call__

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def __call__(self):
        """Get the distribution object from the backend"""
        if get_backend() == 'pytorch':
            import torch.distributions as tod
            raise NotImplementedError
        else:
            import tensorflow as tf
            from tensorflow_probability import distributions as tfd

            # Convert to tensorflow distributions if probflow distributions
            if isinstance(self.distributions, BaseDistribution):
                self.distributions = self.distributions()

            # Broadcast probs/logits
            shape = self.distributions.batch_shape
            args = {'logits': None, 'probs': None}
            if self.logits is not None:
                args['logits'] = tf.broadcast_to(self['logits'], shape)
            else:
                args['probs'] = tf.broadcast_to(self['probs'], shape)

            # Return TFP distribution object
            return tfd.MixtureSameFamily(
                    tfd.Categorical(**args),
                    self.distributions) 
开发者ID:brendanhasz,项目名称:probflow,代码行数:27,代码来源:distributions.py

示例6: _save_model_with_obscurely_shaped_list_output

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def _save_model_with_obscurely_shaped_list_output(export_dir):
  """Writes SavedModel with hard-to-predict output shapes."""
  def broadcast_obscurely_to(input, shape):
    """Like tf.broadcast_to(), but hostile to static shape propagation."""
    obscured_shape = tf.cast(tf.cast(shape, tf.float32)
                             # Add small random noise that gets rounded away.
                             + 0.1*tf.sin(tf.random.uniform((), -3, +3)) + 0.3,
                             tf.int32)
    return tf.broadcast_to(input, obscured_shape)

  @tf.function(
      input_signature=[tf.TensorSpec(shape=(None, 1), dtype=tf.float32)])
  def call_fn(x):
    # For each batch element x, the three outputs are
    #   value x with shape (1)
    #   value 2*x broadcast to shape (2,2)
    #   value 3*x broadcast to shape (3,3,3)
    batch_size = tf.shape(x)[0]
    return [broadcast_obscurely_to(tf.reshape(i*x, [batch_size] + [1]*i),
                                   tf.concat([[batch_size], [i]*i], axis=0))
            for i in range(1, 4)]

  obj = tf.train.Checkpoint()
  obj.__call__ = call_fn
  tf.saved_model.save(obj, export_dir) 
开发者ID:tensorflow,项目名称:hub,代码行数:27,代码来源:keras_layer_test.py

示例7: broadcast_iou

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def broadcast_iou(box_1, box_2):
    # box_1: (..., (x1, y1, x2, y2))
    # box_2: (N, (x1, y1, x2, y2))

    # broadcast boxes
    box_1 = tf.expand_dims(box_1, -2)
    box_2 = tf.expand_dims(box_2, 0)
    # new_shape: (..., N, (x1, y1, x2, y2))
    new_shape = tf.broadcast_dynamic_shape(tf.shape(box_1), tf.shape(box_2))
    box_1 = tf.broadcast_to(box_1, new_shape)
    box_2 = tf.broadcast_to(box_2, new_shape)

    int_w = tf.maximum(tf.minimum(box_1[..., 2], box_2[..., 2]) -
                       tf.maximum(box_1[..., 0], box_2[..., 0]), 0)
    int_h = tf.maximum(tf.minimum(box_1[..., 3], box_2[..., 3]) -
                       tf.maximum(box_1[..., 1], box_2[..., 1]), 0)
    int_area = int_w * int_h
    box_1_area = (box_1[..., 2] - box_1[..., 0]) * \
        (box_1[..., 3] - box_1[..., 1])
    box_2_area = (box_2[..., 2] - box_2[..., 0]) * \
        (box_2[..., 3] - box_2[..., 1])
    return int_area / (box_1_area + box_2_area - int_area) 
开发者ID:microsoft,项目名称:DirectML,代码行数:24,代码来源:utils.py

示例8: _normalize

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def _normalize(image, mean_rgb=MEAN_RGB, stddev_rgb=STDDEV_RGB):
    """Normalizes images to variance 1 and mean 0 over the whole dataset"""

    image -= tf.broadcast_to(mean_rgb, tf.shape(image))
    image /= tf.broadcast_to(stddev_rgb, tf.shape(image))

    return image 
开发者ID:larq,项目名称:zoo,代码行数:9,代码来源:data.py

示例9: sort_key_val

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def sort_key_val(t1, t2, dim=-1):
    values = tf.sort(t1, axis=dim)
    t2 = tf.broadcast_to(t2, t1.shape)
    return values, tf.gather(t2, tf.argsort(t1, axis=dim), axis=dim) 
开发者ID:yyht,项目名称:BERT,代码行数:6,代码来源:reformer_utils.py

示例10: __call__

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def __call__(self, x):
    """Computes regularization using an unbiased Monte Carlo estimate."""
    prior = ed.Independent(
        ed.HalfCauchy(
            loc=tf.broadcast_to(self.loc, x.distribution.event_shape),
            scale=tf.broadcast_to(self.scale, x.distribution.event_shape)
        ).distribution,
        reinterpreted_batch_ndims=len(x.distribution.event_shape))
    negative_entropy = x.distribution.log_prob(x)
    cross_entropy = -prior.distribution.log_prob(x)
    return negative_entropy + cross_entropy 
开发者ID:yyht,项目名称:BERT,代码行数:13,代码来源:regularizers.py

示例11: parameter

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def parameter(input_var,
              length,
              initializer=tf.zeros_initializer(),
              dtype=tf.float32,
              trainable=True,
              name='parameter'):
    """Parameter layer.

    Used as layer that could be broadcast to a certain shape to
    match with input variable during training.

    For recurrent usage, use garage.tf.models.recurrent_parameter().

    Example: A trainable parameter variable with shape (2,), it needs to be
    broadcasted to (32, 2) when applied to a batch with size 32.

    Args:
        input_var (tf.Tensor): Input tf.Tensor.
        length (int): Integer dimension of the variable.
        initializer (callable): Initializer of the variable. The function
            should return a tf.Tensor.
        dtype: Data type of the variable (default is tf.float32).
        trainable (bool): Whether the variable is trainable.
        name (str): Variable scope of the variable.

    Return:
        A tensor of the broadcasted variables.
    """
    with tf.compat.v1.variable_scope(name):
        p = tf.compat.v1.get_variable('parameter',
                                      shape=(length, ),
                                      dtype=dtype,
                                      initializer=initializer,
                                      trainable=trainable)
        batch_dim = tf.shape(input_var)[0]
        broadcast_shape = tf.concat(axis=0, values=[[batch_dim], [length]])
        p_broadcast = tf.broadcast_to(p, shape=broadcast_shape)
        return p_broadcast 
开发者ID:rlworkgroup,项目名称:garage,代码行数:40,代码来源:parameter.py

示例12: eval_image

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def eval_image(image, height, width, resize_method,
               central_fraction=0.875, scope=None):

  with tf.compat.v1.name_scope('eval_image'):
    if resize_method == 'crop':
      shape = tf.shape(input=image)
      image = tf.cond(pred=tf.less(shape[0], shape[1]),
                      true_fn=lambda: tf.image.resize(image,
                                                     tf.convert_to_tensor(value=[256, 256 * shape[1] / shape[0]],
                                                                          dtype=tf.int32)),
                      false_fn=lambda: tf.image.resize(image,
                                                     tf.convert_to_tensor(value=[256 * shape[0] / shape[1], 256],
                                                                          dtype=tf.int32)))

      shape = tf.shape(input=image)
      y0 = (shape[0] - height) // 2
      x0 = (shape[1] - width) // 2
      distorted_image = tf.image.crop_to_bounding_box(image, y0, x0, height, width)
      distorted_image.set_shape([height, width, 3])
      means = tf.broadcast_to([123.68, 116.78, 103.94], tf.shape(input=distorted_image))
      return distorted_image - means
    else:  # bilinear
      if image.dtype != tf.float32:
        image = tf.image.convert_image_dtype(image, dtype=tf.float32)
      # Crop the central region of the image with an area containing 87.5% of
      # the original image.
      if central_fraction:
        image = tf.image.central_crop(image, central_fraction=central_fraction)

      if height and width:
        # Resize the image to the specified height and width.
        image = tf.expand_dims(image, 0)
        image = tf.image.resize(image, [height, width],
                                         method=tf.image.ResizeMethod.BILINEAR)
        image = tf.squeeze(image, [0])
      image = tf.subtract(image, 0.5)
      image = tf.multiply(image, 2.0)
      return image 
开发者ID:IntelAI,项目名称:models,代码行数:40,代码来源:preprocessing.py

示例13: eval_image

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def eval_image(image, height, width, resize_method,
               central_fraction=0.875, scope=None):
  with tf.compat.v1.name_scope('eval_image'):
    if resize_method == 'crop':
      shape = tf.shape(input=image)
      image = tf.cond(pred=tf.less(shape[0], shape[1]),
                      true_fn=lambda: tf.image.resize(image,
                                                     tf.convert_to_tensor(value=[256, 256 * shape[1] / shape[0]],
                                                                          dtype=tf.int32)),
                      false_fn=lambda: tf.image.resize(image,
                                                     tf.convert_to_tensor(value=[256 * shape[0] / shape[1], 256],
                                                                          dtype=tf.int32)))
      shape = tf.shape(input=image)
      y0 = (shape[0] - height) // 2
      x0 = (shape[1] - width) // 2
      distorted_image = tf.image.crop_to_bounding_box(image, y0, x0, height, width)
      distorted_image.set_shape([height, width, 3])
      means = tf.broadcast_to([123.68, 116.78, 103.94], tf.shape(input=distorted_image))
      return distorted_image - means
    else:  # bilinear
      if image.dtype != tf.float32:
        image = tf.image.convert_image_dtype(image, dtype=tf.float32)
      # Crop the central region of the image with an area containing 87.5% of
      # the original image.
      if central_fraction:
        image = tf.image.central_crop(image, central_fraction=central_fraction)

      if height and width:
        # Resize the image to the specified height and width.
        image = tf.expand_dims(image, 0)
        image = tf.image.resize(image, [height, width],
                                         method=tf.image.ResizeMethod.BILINEAR)
        image = tf.squeeze(image, [0])
      image = tf.subtract(image, 0.5)
      image = tf.multiply(image, 2.0)
      return image 
开发者ID:IntelAI,项目名称:models,代码行数:38,代码来源:preprocessing_benchmark.py

示例14: test_rotate_zonal_harmonics_random

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def test_rotate_zonal_harmonics_random(self):
    """Tests the outputs of test_rotate_zonal_harmonics."""
    dtype = tf.float64
    max_band = 2
    zonal_coeffs = tf.constant(
        np.random.uniform(-1.0, 1.0, size=[3]), dtype=dtype)
    tensor_size = np.random.randint(3)
    tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist()
    theta = tf.constant(
        np.random.uniform(0.0, np.pi, size=tensor_shape + [1]), dtype=dtype)
    phi = tf.constant(
        np.random.uniform(0.0, 2.0 * np.pi, size=tensor_shape + [1]),
        dtype=dtype)

    rotated_zonal_coeffs = spherical_harmonics.rotate_zonal_harmonics(
        zonal_coeffs, theta, phi)
    zonal_coeffs = spherical_harmonics.tile_zonal_coefficients(zonal_coeffs)
    l, m = spherical_harmonics.generate_l_m_permutations(max_band)
    l = tf.broadcast_to(l, tensor_shape + l.shape.as_list())
    m = tf.broadcast_to(m, tensor_shape + m.shape.as_list())
    theta_zero = tf.constant(0.0, shape=tensor_shape + [1], dtype=dtype)
    phi_zero = tf.constant(0.0, shape=tensor_shape + [1], dtype=dtype)
    gt = zonal_coeffs * spherical_harmonics.evaluate_spherical_harmonics(
        l, m, theta_zero, phi_zero)
    gt = tf.reduce_sum(input_tensor=gt, axis=-1)
    pred = rotated_zonal_coeffs * spherical_harmonics.evaluate_spherical_harmonics(
        l, m, theta + theta_zero, phi + phi_zero)
    pred = tf.reduce_sum(input_tensor=pred, axis=-1)

    self.assertAllClose(gt, pred) 
开发者ID:tensorflow,项目名称:graphics,代码行数:32,代码来源:spherical_harmonics_test.py

示例15: call

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import broadcast_to [as 别名]
def call(self, x, y, training=None):
        x = self.up(x)
        x = self.bn(x, training=None)
        w_conf = tf.nn.softmax(x)
        axis = get_channel_axis(self.data_format)
        w_max = tf.broadcast_to(tf.expand_dims(tf.reduce_max(w_conf, axis=axis), axis=axis), shape=x.shape)
        x = y * (1 - w_max) + x
        return x 
开发者ID:osmr,项目名称:imgclsmob,代码行数:10,代码来源:sinet.py


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