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


Python tensorflow.to_float方法代码示例

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


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

示例1: create_test_input

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def create_test_input(batch_size, height, width, channels):
  """Create test input tensor.

  Args:
    batch_size: The number of images per batch or `None` if unknown.
    height: The height of each image or `None` if unknown.
    width: The width of each image or `None` if unknown.
    channels: The number of channels per image or `None` if unknown.

  Returns:
    Either a placeholder `Tensor` of dimension
      [batch_size, height, width, channels] if any of the inputs are `None` or a
    constant `Tensor` with the mesh grid values along the spatial dimensions.
  """
  if None in [batch_size, height, width, channels]:
    return tf.placeholder(tf.float32, (batch_size, height, width, channels))
  else:
    return tf.to_float(
        np.tile(
            np.reshape(
                np.reshape(np.arange(height), [height, 1]) +
                np.reshape(np.arange(width), [1, width]),
                [1, height, width, 1]),
            [batch_size, 1, 1, channels])) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:26,代码来源:resnet_v2_test.py

示例2: preprocess_image

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def preprocess_image(image, output_height, output_width, is_training):
  """Preprocesses the given image.

  Args:
    image: A `Tensor` representing an image of arbitrary size.
    output_height: The height of the image after preprocessing.
    output_width: The width of the image after preprocessing.
    is_training: `True` if we're preprocessing the image for training and
      `False` otherwise.

  Returns:
    A preprocessed image.
  """
  image = tf.to_float(image)
  image = tf.image.resize_image_with_crop_or_pad(
      image, output_width, output_height)
  image = tf.subtract(image, 128.0)
  image = tf.div(image, 128.0)
  return image 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:21,代码来源:lenet_preprocessing.py

示例3: preprocess_for_eval

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def preprocess_for_eval(image, output_height, output_width, resize_side):
  """Preprocesses the given image for evaluation.

  Args:
    image: A `Tensor` representing an image of arbitrary size.
    output_height: The height of the image after preprocessing.
    output_width: The width of the image after preprocessing.
    resize_side: The smallest side of the image for aspect-preserving resizing.

  Returns:
    A preprocessed image.
  """
  image = _aspect_preserving_resize(image, resize_side)
  image = _central_crop([image], output_height, output_width)[0]
  image.set_shape([output_height, output_width, 3])
  image = tf.to_float(image)
  return _mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN]) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:19,代码来源:vgg_preprocessing.py

示例4: preprocess_for_eval

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def preprocess_for_eval(image, output_height, output_width):
  """Preprocesses the given image for evaluation.

  Args:
    image: A `Tensor` representing an image of arbitrary size.
    output_height: The height of the image after preprocessing.
    output_width: The width of the image after preprocessing.

  Returns:
    A preprocessed image.
  """
  tf.summary.image('image', tf.expand_dims(image, 0))
  # Transform the image to floats.
  image = tf.to_float(image)

  # Resize and crop if needed.
  resized_image = tf.image.resize_image_with_crop_or_pad(image,
                                                         output_width,
                                                         output_height)
  tf.summary.image('resized_image', tf.expand_dims(resized_image, 0))

  # Subtract off the mean and divide by the variance of the pixels.
  return tf.image.per_image_standardization(resized_image) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:25,代码来源:cifarnet_preprocessing.py

示例5: pass_through_embedding_matrix

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def pass_through_embedding_matrix(act_block, embedding_matrix, step_idx):
  """Passes the activations through the embedding_matrix.

  Takes care to handle out of bounds lookups.

  Args:
    act_block: matrix of activations.
    embedding_matrix: matrix of weights.
    step_idx: vector containing step indices, with -1 indicating out of bounds.

  Returns:
    the embedded activations.
  """
  # Indicator vector for out of bounds lookups.
  step_idx_mask = tf.expand_dims(tf.equal(step_idx, -1), -1)

  # Pad the last column of the activation vectors with the indicator.
  act_block = tf.concat([act_block, tf.to_float(step_idx_mask)], 1)
  return tf.matmul(act_block, embedding_matrix) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:21,代码来源:network_units.py

示例6: _export_inference_graph

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def _export_inference_graph(input_type,
                            detection_model,
                            use_moving_averages,
                            checkpoint_path,
                            inference_graph_path,
                            export_as_saved_model=False):
  """Export helper."""
  if input_type not in input_placeholder_fn_map:
    raise ValueError('Unknown input type: {}'.format(input_type))
  inputs = tf.to_float(input_placeholder_fn_map[input_type]())
  preprocessed_inputs = detection_model.preprocess(inputs)
  output_tensors = detection_model.predict(preprocessed_inputs)
  postprocessed_tensors = detection_model.postprocess(output_tensors)
  outputs = _add_output_tensor_nodes(postprocessed_tensors)
  out_node_names = list(outputs.keys())
  if export_as_saved_model:
    _write_saved_model(inference_graph_path, inputs, outputs, checkpoint_path,
                       use_moving_averages)
  else:
    _write_inference_graph(inference_graph_path, checkpoint_path,
                           use_moving_averages,
                           output_node_names=','.join(out_node_names)) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:24,代码来源:exporter.py

示例7: __init__

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def __init__(self, num_keypoints, scale_factors=None):
    """Constructor for KeypointBoxCoder.

    Args:
      num_keypoints: Number of keypoints to encode/decode.
      scale_factors: List of 4 positive scalars to scale ty, tx, th and tw.
        In addition to scaling ty and tx, the first 2 scalars are used to scale
        the y and x coordinates of the keypoints as well. If set to None, does
        not perform scaling.
    """
    self._num_keypoints = num_keypoints

    if scale_factors:
      assert len(scale_factors) == 4
      for scalar in scale_factors:
        assert scalar > 0
    self._scale_factors = scale_factors
    self._keypoint_scale_factors = None
    if scale_factors is not None:
      self._keypoint_scale_factors = tf.expand_dims(tf.tile(
          [tf.to_float(scale_factors[0]), tf.to_float(scale_factors[1])],
          [num_keypoints]), 1) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:24,代码来源:keypoint_box_coder.py

示例8: testRandomPixelValueScale

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def testRandomPixelValueScale(self):
    preprocessing_options = []
    preprocessing_options.append((preprocessor.normalize_image, {
        'original_minval': 0,
        'original_maxval': 255,
        'target_minval': 0,
        'target_maxval': 1
    }))
    preprocessing_options.append((preprocessor.random_pixel_value_scale, {}))
    images = self.createTestImages()
    tensor_dict = {fields.InputDataFields.image: images}
    tensor_dict = preprocessor.preprocess(tensor_dict, preprocessing_options)
    images_min = tf.to_float(images) * 0.9 / 255.0
    images_max = tf.to_float(images) * 1.1 / 255.0
    images = tensor_dict[fields.InputDataFields.image]
    values_greater = tf.greater_equal(images, images_min)
    values_less = tf.less_equal(images, images_max)
    values_true = tf.fill([1, 4, 4, 3], True)
    with self.test_session() as sess:
      (values_greater_, values_less_, values_true_) = sess.run(
          [values_greater, values_less, values_true])
      self.assertAllClose(values_greater_, values_true_)
      self.assertAllClose(values_less_, values_true_) 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:25,代码来源:preprocessor_test.py

示例9: compute_upsample_values

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def compute_upsample_values(input_tensor, upsample_height, upsample_width):
  """Compute values for an upsampling op (ops.BatchCropAndResize).

  Args:
    input_tensor: image tensor with shape [batch, height, width, in_channels]
    upsample_height: integer
    upsample_width: integer

  Returns:
    grid_centers: tensor with shape [batch, 1]
    crop_sizes: tensor with shape [batch, 1]
    output_height: integer
    output_width: integer
  """
  batch, input_height, input_width, _ = input_tensor.shape

  height_half = input_height / 2.
  width_half = input_width / 2.
  grid_centers = tf.constant(batch * [[height_half, width_half]])
  crop_sizes = tf.constant(batch * [[input_height, input_width]])
  output_height = input_height * upsample_height
  output_width = input_width * upsample_width

  return grid_centers, tf.to_float(crop_sizes), output_height, output_width 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:26,代码来源:utils.py

示例10: _testBuildDefaultModel

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def _testBuildDefaultModel(self):
    images = tf.to_float(np.random.rand(32, 28, 28, 1))
    labels = {}
    labels['classes'] = tf.one_hot(
        tf.to_int32(np.random.randint(0, 9, (32))), 10)

    params = {
        'use_separation': True,
        'layers_to_regularize': 'fc3',
        'weight_decay': 0.0,
        'ps_tasks': 1,
        'domain_separation_startpoint': 1,
        'alpha_weight': 1,
        'beta_weight': 1,
        'gamma_weight': 1,
        'recon_loss_name': 'sum_of_squares',
        'decoder_name': 'small_decoder',
        'encoder_name': 'default_encoder',
    }
    return images, labels, params 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:22,代码来源:dsn_test.py

示例11: padded_accuracy_topk

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def padded_accuracy_topk(predictions,
                         labels,
                         k,
                         weights_fn=common_layers.weights_nonzero):
  """Percentage of times that top-k predictions matches labels on non-0s."""
  with tf.variable_scope("padded_accuracy_topk", values=[predictions, labels]):
    padded_predictions, padded_labels = common_layers.pad_with_zeros(
        predictions, labels)
    weights = weights_fn(padded_labels)
    effective_k = tf.minimum(k,
                             common_layers.shape_list(padded_predictions)[-1])
    _, outputs = tf.nn.top_k(padded_predictions, k=effective_k)
    outputs = tf.to_int32(outputs)
    padded_labels = tf.to_int32(padded_labels)
    padded_labels = tf.expand_dims(padded_labels, axis=-1)
    padded_labels += tf.zeros_like(outputs)  # Pad to same shape.
    same = tf.to_float(tf.equal(outputs, padded_labels))
    same_topk = tf.reduce_sum(same, axis=-1)
    return same_topk, weights 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:21,代码来源:metrics.py

示例12: set_precision

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def set_precision(predictions, labels,
                  weights_fn=common_layers.weights_nonzero):
  """Precision of set predictions.

  Args:
    predictions : A Tensor of scores of shape [batch, nlabels].
    labels: A Tensor of int32s giving true set elements,
      of shape [batch, seq_length].
    weights_fn: A function to weight the elements.

  Returns:
    hits: A Tensor of shape [batch, nlabels].
    weights: A Tensor of shape [batch, nlabels].
  """
  with tf.variable_scope("set_precision", values=[predictions, labels]):
    labels = tf.squeeze(labels, [2, 3])
    weights = weights_fn(labels)
    labels = tf.one_hot(labels, predictions.shape[-1])
    labels = tf.reduce_max(labels, axis=1)
    labels = tf.cast(labels, tf.bool)
    return tf.to_float(tf.equal(labels, predictions)), weights 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:23,代码来源:metrics.py

示例13: set_recall

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def set_recall(predictions, labels, weights_fn=common_layers.weights_nonzero):
  """Recall of set predictions.

  Args:
    predictions : A Tensor of scores of shape [batch, nlabels].
    labels: A Tensor of int32s giving true set elements,
      of shape [batch, seq_length].
    weights_fn: A function to weight the elements.

  Returns:
    hits: A Tensor of shape [batch, nlabels].
    weights: A Tensor of shape [batch, nlabels].
  """
  with tf.variable_scope("set_recall", values=[predictions, labels]):
    labels = tf.squeeze(labels, [2, 3])
    weights = weights_fn(labels)
    labels = tf.one_hot(labels, predictions.shape[-1])
    labels = tf.reduce_max(labels, axis=1)
    labels = tf.cast(labels, tf.bool)
    return tf.to_float(tf.equal(labels, predictions)), weights 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:22,代码来源:metrics.py

示例14: cv_squared

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def cv_squared(x):
  """The squared coefficient of variation of a sample.

  Useful as a loss to encourage a positive distribution to be more uniform.
  Epsilons added for numerical stability.
  Returns 0 for an empty Tensor.

  Args:
    x: a `Tensor`.

  Returns:
    a `Scalar`.
  """
  epsilon = 1e-10
  float_size = tf.to_float(tf.size(x)) + epsilon
  mean = tf.reduce_sum(x) / float_size
  variance = tf.reduce_sum(tf.square(x - mean)) / float_size
  return variance / (tf.square(mean) + epsilon) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:20,代码来源:expert_utils.py

示例15: diet_expert

# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import to_float [as 别名]
def diet_expert(x, hidden_size, params):
  """A two-layer feed-forward network with relu activation on hidden layer.

  Uses diet variables.
  Recomputes hidden layer on backprop to save activation memory.

  Args:
    x: a Tensor with shape [batch, io_size]
    hidden_size: an integer
    params: a diet variable HParams object.

  Returns:
    a Tensor with shape [batch, io_size]
  """

  @fn_with_diet_vars(params)
  def diet_expert_internal(x):
    dim = x.get_shape().as_list()[-1]
    h = tf.layers.dense(x, hidden_size, activation=tf.nn.relu, use_bias=False)
    y = tf.layers.dense(h, dim, use_bias=False)
    y *= tf.rsqrt(tf.to_float(dim * hidden_size))
    return y

  return diet_expert_internal(x) 
开发者ID:akzaidi,项目名称:fine-lm,代码行数:26,代码来源:diet.py


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