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


Python v2.reduce_sum方法代码示例

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


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

示例1: test_randomized_qmc_basic

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def test_randomized_qmc_basic(self):
    """Tests the randomization of the random.halton sequences."""
    # This test is identical to the example given in Owen (2017), Figure 5.
    dim = 20
    num_results = 2000
    replica = 5
    seed = 121117

    values = []
    for i in range(replica):
      sample, _ = random.halton.sample(dim, num_results=num_results,
                                       seed=seed + i)
      f = tf.reduce_mean(
          input_tensor=tf.reduce_sum(input_tensor=sample, axis=1)**2)
      values.append(self.evaluate(f))
    self.assertAllClose(np.mean(values), 101.6667, atol=np.std(values) * 2) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:18,代码来源:halton_test.py

示例2: labels_of_top_ranked_predictions_in_batch

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def labels_of_top_ranked_predictions_in_batch(labels, predictions):
  """Applying tf.metrics.mean to this gives precision at 1.

  Args:
    labels: minibatch of dense 0/1 labels, shape [batch_size rows, num_classes]
    predictions: minibatch of predictions of the same shape

  Returns:
    one-dimension tensor top_labels, where top_labels[i]=1.0 iff the
    top-scoring prediction for batch element i has label 1.0
  """
  indices_of_top_preds = tf.cast(tf.argmax(input=predictions, axis=1), tf.int32)
  batch_size = tf.reduce_sum(input_tensor=tf.ones_like(indices_of_top_preds))
  row_indices = tf.range(batch_size)
  thresholded_labels = tf.where(labels > 0.0, tf.ones_like(labels),
                                tf.zeros_like(labels))
  label_indices_to_gather = tf.transpose(
      a=tf.stack([row_indices, indices_of_top_preds]))
  return tf.gather_nd(thresholded_labels, label_indices_to_gather) 
开发者ID:google-research,项目名称:language,代码行数:21,代码来源:util.py

示例3: weighted_by_sum

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def weighted_by_sum(
      self, other):
    """Weight elements in some set by the sum of the scores in some other set.

    Args:
      other: A NeuralQueryExpression

    Returns:
      The NeuralQueryExpression that evaluates to the reweighted version of
    the set obtained by evaluating 'self'.
    """
    provenance = NQExprProvenance(
        operation='weighted_by_sum',
        inner=self.provenance,
        other=other.provenance)
    with tf.name_scope('weighted_by_sum'):
      return self.context.as_nql(
          self.tf * tf.reduce_sum(input_tensor=other.tf, axis=1, keepdims=True),
          self._type_name, provenance) 
开发者ID:google-research,项目名称:language,代码行数:21,代码来源:__init__.py

示例4: nonneg_crossentropy

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def nonneg_crossentropy(expr, target):
  """A cross entropy operator that is appropriate for NQL outputs.

  Query expressions often evaluate to sparse vectors.  This evaluates cross
  entropy safely.

  Args:
    expr: a Tensorflow expression for some predicted values.
    target: a Tensorflow expression for target values.

  Returns:
    Tensorflow expression for cross entropy.
  """
  expr_replacing_0_with_1 = \
     tf.where(expr > 0, expr, tf.ones(tf.shape(input=expr), tf.float32))
  cross_entropies = tf.reduce_sum(
      input_tensor=-target * tf.math.log(expr_replacing_0_with_1), axis=1)
  return tf.reduce_mean(input_tensor=cross_entropies, axis=0) 
开发者ID:google-research,项目名称:language,代码行数:20,代码来源:__init__.py

示例5: sum

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def sum(a, axis=None, dtype=None, keepdims=None):  # pylint: disable=redefined-builtin
  return _reduce(tf.reduce_sum, a, axis=axis, dtype=dtype, keepdims=keepdims,
                 tf_bool_fn=tf.reduce_any) 
开发者ID:google,项目名称:trax,代码行数:5,代码来源:array_ops.py

示例6: safe_mean

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def safe_mean(losses):
  total = tf.reduce_sum(losses)
  num_elements = tf.dtypes.cast(tf.size(losses), dtype=losses.dtype)
  return tf.math.divide_no_nan(total, num_elements) 
开发者ID:artyompal,项目名称:tpu_models,代码行数:6,代码来源:resnet50_ctl_tf2.py

示例7: _init_norm

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def _init_norm(self):
        """Set the norm of the weight vector."""
        kernel_norm = tf.sqrt(tf.reduce_sum(tf.square(self.v), axis=self.kernel_norm_axes))
        self.g.assign(kernel_norm) 
开发者ID:SeldonIO,项目名称:alibi-detect,代码行数:6,代码来源:pixelcnn.py

示例8: call

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def call(self, y_true, y_pred):
    """See _RankingLoss."""
    losses, weights = self._loss.compute_unreduced_loss(
        labels=y_true, logits=y_pred)
    losses = tf.multiply(losses, weights)
    # [batch_size, list_size, list_size]
    losses.get_shape().assert_has_rank(3)
    # Reduce the loss along the last dim so that weights ([batch_size, 1] or
    # [batch_size, list_size] can be applied in __call__.
    return tf.reduce_sum(losses, axis=2) 
开发者ID:tensorflow,项目名称:ranking,代码行数:12,代码来源:losses.py

示例9: _randomize

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def _randomize(coeffs, radixes, seed, perms=None):
  """Applies the Owen (2017) randomization to the coefficients."""
  given_dtype = coeffs.dtype
  coeffs = tf.cast(coeffs, dtype=tf.int32)
  num_coeffs = _NUM_COEFFS_BY_DTYPE[given_dtype]
  radixes = tf.reshape(tf.cast(radixes, dtype=tf.int32), shape=[-1])
  if perms is None:
    perms = _get_permutations(num_coeffs, radixes, seed)
    perms = tf.reshape(perms, shape=[-1])
  radix_sum = tf.reduce_sum(input_tensor=radixes)
  radix_offsets = tf.reshape(tf.cumsum(radixes, exclusive=True), shape=[-1, 1])
  offsets = radix_offsets + tf.range(num_coeffs) * radix_sum
  permuted_coeffs = tf.gather(perms, coeffs + offsets)
  return tf.cast(permuted_coeffs, dtype=given_dtype), perms 
开发者ID:google,项目名称:tf-quant-finance,代码行数:16,代码来源:halton_impl.py

示例10: test_make_val_and_grad_fn

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def test_make_val_and_grad_fn(self):
    minimum = np.array([1.0, 1.0])
    scales = np.array([2.0, 3.0])

    @tff.math.make_val_and_grad_fn
    def quadratic(x):
      return tf.reduce_sum(input_tensor=scales * (x - minimum)**2)

    point = tf.constant([2.0, 2.0], dtype=tf.float64)
    val, grad = self.evaluate(quadratic(point))
    self.assertNear(val, 5.0, 1e-5)
    self.assertArrayNear(grad, [4.0, 6.0], 1e-5) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:14,代码来源:gradient_test.py

示例11: make_val_and_grad_fn

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def make_val_and_grad_fn(value_fn):
  """Function decorator to compute both function value and gradient.

  For example:

  ```
  @tff.math.make_val_and_grad_fn
  def quadratic(x):
    return tf.reduce_sum(scales * (x - minimum) ** 2, axis=-1)
  ```

  Turns `quadratic` into a function that accepts a point as a `Tensor` as input
  and returns a tuple of two `Tensor`s with the value and the gradient of the
  defined quadratic function evaluated at the input point.

  This is useful for constucting functions to optimize with tff.math.optimizer
  methods.

  Args:
    value_fn: A python function to decorate.

  Returns:
    The decorated function.
  """
  @functools.wraps(value_fn)
  def val_and_grad(x):
    return value_and_gradient(value_fn, x)

  return val_and_grad 
开发者ID:google,项目名称:tf-quant-finance,代码行数:31,代码来源:gradient.py

示例12: test_differential_evolution

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def test_differential_evolution(self):
    """Use differential evolution algorithm to minimize a quadratic function."""
    minimum = np.array([1.0, 1.0])
    scales = np.array([2.0, 3.0])
    def quadratic(x):
      return tf.reduce_sum(
          scales * tf.math.squared_difference(x, minimum), axis=-1)

    initial_population = tf.random.uniform([40, 2], seed=1243)
    results = self.evaluate(tff_math.optimizer.differential_evolution_minimize(
        quadratic,
        initial_population=initial_population,
        func_tolerance=1e-12,
        seed=2484))
    self.assertTrue(results.converged) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:17,代码来源:optimizer_test.py

示例13: _rosenbrock

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def _rosenbrock(x):
  """See https://en.wikipedia.org/wiki/Rosenbrock_function."""
  term1 = 100 * tf.reduce_sum(tf.square(x[1:] - tf.square(x[:-1])))
  term2 = tf.reduce_sum(tf.square(1 - x[:-1]))
  return term1 + term2 
开发者ID:google,项目名称:tf-quant-finance,代码行数:7,代码来源:conjugate_gradient_test.py

示例14: test_paraboloid_4th_order

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def test_paraboloid_4th_order(self):
    self._check_algorithm(
        func=lambda x: tf.reduce_sum(x**4),
        start_point=[1, 2, 3, 4, 5],
        expected_argmin=[0, 0, 0, 0, 0],
        gtol=1e-10) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:8,代码来源:conjugate_gradient_test.py

示例15: test_logistic_regression

# 需要导入模块: from tensorflow.compat import v2 [as 别名]
# 或者: from tensorflow.compat.v2 import reduce_sum [as 别名]
def test_logistic_regression(self):
    dim = 5
    n_objs = 10000
    np.random.seed(1)
    betas = np.random.randn(dim)  # The true beta
    intercept = np.random.randn()  # The true intercept
    features = np.random.randn(n_objs, dim)  # The feature matrix
    probs = 1 / (1 + np.exp(
        -np.matmul(features, np.expand_dims(betas, -1)) - intercept))
    labels = np.random.binomial(1, probs)  # The true labels
    regularization = 0.8
    feat = tf.constant(features, dtype=tf.float64)
    lab = tf.constant(labels, dtype=feat.dtype)

    def f_negative_log_likelihood(params):
      intercept, beta = params[0], params[1:]
      logit = tf.matmul(feat, tf.expand_dims(beta, -1)) + intercept
      log_likelihood = tf.reduce_sum(
          tf.nn.sigmoid_cross_entropy_with_logits(labels=lab, logits=logit))
      l2_penalty = regularization * tf.reduce_sum(beta**2)
      total_loss = log_likelihood + l2_penalty
      return total_loss
    start_point = np.ones(dim + 1)
    argmin = [
        -2.38636155, 1.61778325, -0.60694238, -0.51523609, -1.09832275,
        0.88892742
    ]

    self._check_algorithm(
        func=f_negative_log_likelihood,
        start_point=start_point,
        expected_argmin=argmin,
        gtol=1e-5) 
开发者ID:google,项目名称:tf-quant-finance,代码行数:35,代码来源:conjugate_gradient_test.py


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