• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python math_ops.segment_sum函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tensorflow.python.ops.math_ops.segment_sum函数的典型用法代码示例。如果您正苦于以下问题:Python segment_sum函数的具体用法?Python segment_sum怎么用?Python segment_sum使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: body

    def body(it, cost):
      embedding = embedding_ops.embedding_lookup(embedding_matrix, [0])
      cost = control_flow_ops.cond(
          math_ops.equal(it, 3), lambda: math_ops.square(cost),
          (lambda: cost + math_ops.reduce_sum(embedding)))
      return it + 1, cost

      _, cost = control_flow_ops.while_loop(
          cond, body, [constant_op.constant(0),
                       constant_op.constant(0.0)])

      dynamic_grads = gradients_impl.gradients(cost, [embedding_matrix])[0]
      dynamic_grads = math_ops.segment_sum(dynamic_grads.values,
                                           dynamic_grads.indices)

      embedding = embedding_ops.embedding_lookup(embedding_matrix, [0])
      static = math_ops.square(
          math_ops.reduce_sum(embedding) + math_ops.reduce_sum(embedding) +
          math_ops.reduce_sum(embedding)) + math_ops.reduce_sum(embedding)
      static_grads = gradients_impl.gradients(static, [embedding_matrix])[0]
      static_grads = math_ops.segment_sum(static_grads.values,
                                          static_grads.indices)

      with self.cached_session():
        self.evaluate(variables.global_variables_initializer())
        self.assertAllEqual(*self.evaluate([static_grads, dynamic_grads]))
开发者ID:Wajih-O,项目名称:tensorflow,代码行数:26,代码来源:control_flow_ops_test.py


示例2: doTestIndexedSlicesGradientInCondInWhileLoop

  def doTestIndexedSlicesGradientInCondInWhileLoop(self, use_resource=False):
    with ops.Graph().as_default():
      embedding_matrix = variable_scope.get_variable(
          "embedding_matrix", [5, 5],
          initializer=init_ops.random_normal_initializer(),
          use_resource=use_resource)

      def Cond(it, _):
        return it < 5

      def Body(it, cost):
        embedding = embedding_ops.embedding_lookup(embedding_matrix, [0])
        cost = control_flow_ops.cond(
            math_ops.equal(it, 3), lambda: math_ops.square(cost),
            lambda: cost + math_ops.reduce_sum(embedding))
        return it + 1, cost

      _, cost = control_flow_ops.while_loop(
          Cond, Body, [constant_op.constant(0), constant_op.constant(0.0)])

      dynamic_grads = gradients_impl.gradients(cost, [embedding_matrix])[0]
      dynamic_grads = math_ops.segment_sum(dynamic_grads.values,
                                           dynamic_grads.indices)

      embedding = embedding_ops.embedding_lookup(embedding_matrix, [0])
      static = math_ops.square(
          math_ops.reduce_sum(embedding) + math_ops.reduce_sum(embedding) +
          math_ops.reduce_sum(embedding)) + math_ops.reduce_sum(embedding)
      static_grads = gradients_impl.gradients(static, [embedding_matrix])[0]
      static_grads = math_ops.segment_sum(static_grads.values,
                                          static_grads.indices)

      with self.test_session() as sess:
        sess.run(variables.global_variables_initializer())
        self.assertAllEqual(*sess.run([static_grads, dynamic_grads]))
开发者ID:AlbertXiebnu,项目名称:tensorflow,代码行数:35,代码来源:control_flow_ops_test.py


示例3: testGradientMatchesSegmentSum

  def testGradientMatchesSegmentSum(self):
    # Strategy: compute the gradient for UnsortedSegmentSum and SegmentSum
    # and compare the outputs, which should be identical.
    # NB: for this test to work, indices must be valid for SegmentSum, namely
    # it must be sorted, the indices must be contiguous, and num_segments
    # must be max(indices) + 1.
    indices = [0, 0, 1, 1, 1, 2, 3, 4, 5]
    n = len(indices)
    num_cols = 2
    shape = [n, num_cols]
    num_segments = max(indices) + 1
    for dtype in self.differentiable_dtypes:
      with self.cached_session(use_gpu=True):
        tf_x, np_x = self._input(shape, dtype=dtype)
        # Results from UnsortedSegmentSum
        unsorted_s = math_ops.unsorted_segment_sum(
            data=tf_x, segment_ids=indices, num_segments=num_segments)
        unsorted_jacob_t, unsorted_jacob_n = (
            gradient_checker.compute_gradient(tf_x, shape, unsorted_s,
                                              [num_segments, num_cols],
                                              x_init_value=np_x, delta=1))

        # Results from SegmentSum
        sorted_s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
        sorted_jacob_t, sorted_jacob_n = gradient_checker.compute_gradient(
            tf_x,
            shape,
            sorted_s, [num_segments, num_cols],
            x_init_value=np_x,
            delta=1)
      self.assertAllClose(unsorted_jacob_t, sorted_jacob_t)
      self.assertAllClose(unsorted_jacob_n, sorted_jacob_n)
开发者ID:abhinav-upadhyay,项目名称:tensorflow,代码行数:32,代码来源:segment_reduction_ops_test.py


示例4: testSegmentIdsInvalid2

 def testSegmentIdsInvalid2(self):
   shape = [4, 4]
   with self.test_session():
     tf_x, _ = self._input(shape)
     indices = [1, 1, 2, 2]
     s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
     with self.assertRaisesOpError("segment ids do not start at 0"):
       s.eval()
开发者ID:AliMiraftab,项目名称:tensorflow,代码行数:8,代码来源:segment_reduction_ops_test.py


示例5: testSegmentIdsInvalid2

 def testSegmentIdsInvalid2(self):
   shape = [4, 4]
   with self.cached_session():
     tf_x, _ = self._input(shape)
     indices = [0, 1, 0, 1]
     s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
     with self.assertRaisesOpError("segment ids are not increasing"):
       s.eval()
开发者ID:abhinav-upadhyay,项目名称:tensorflow,代码行数:8,代码来源:segment_reduction_ops_test.py


示例6: testSegmentIdsInvalid5

 def testSegmentIdsInvalid5(self):
   shape = [4, 4]
   with self.test_session():
     tf_x, _ = self._input(shape)
     indices = [0, 0, 0, -2]
     s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
     with self.assertRaisesOpError("segment ids must be >= 0"):
       s.eval()
开发者ID:AlbertXiebnu,项目名称:tensorflow,代码行数:8,代码来源:segment_reduction_ops_test.py


示例7: testSegmentIdsValid

 def testSegmentIdsValid(self):
   # This is a baseline for the following SegmentIdsInvalid* tests.
   shape = [4, 4]
   with self.test_session():
     tf_x, _ = self._input(shape)
     indices = [0, 0, 0, 1]
     result = math_ops.segment_sum(data=tf_x, segment_ids=indices).eval()
     self.assertAllEqual([[15, 18, 21, 24], [13, 14, 15, 16]], result)
开发者ID:AlbertXiebnu,项目名称:tensorflow,代码行数:8,代码来源:segment_reduction_ops_test.py


示例8: testSegmentIdsSize

 def testSegmentIdsSize(self):
   shape = [4, 4]
   with self.test_session():
     tf_x, _ = self._input(shape)
     indices = [0, 1]
     s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
     with self.assertRaisesOpError("segment_ids should be the same size"):
       s.eval()
开发者ID:AlbertXiebnu,项目名称:tensorflow,代码行数:8,代码来源:segment_reduction_ops_test.py


示例9: testSegmentIdsInvalid5

 def testSegmentIdsInvalid5(self):
   shape = [4, 4]
   for use_gpu in [True, False]:
     with self.cached_session(use_gpu=use_gpu):
       tf_x, _ = self._input(shape, dtype=dtypes_lib.float32)
       indices = [0, 0, 0, -2]
       s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
       with self.assertRaisesOpError("segment ids must be >= 0"):
         s.eval()
开发者ID:abhinav-upadhyay,项目名称:tensorflow,代码行数:9,代码来源:segment_reduction_ops_test.py


示例10: testSegmentIdsValid

 def testSegmentIdsValid(self):
   # This is a baseline for the following SegmentIdsInvalid* tests.
   shape = [4, 4]
   for use_gpu in [True, False]:
     with self.cached_session(use_gpu=use_gpu):
       tf_x, _ = self._input(shape, dtype=dtypes_lib.float32)
       indices = [0, 0, 0, 1]
       result = math_ops.segment_sum(data=tf_x, segment_ids=indices).eval()
       self.assertAllEqual([[15, 18, 21, 24], [13, 14, 15, 16]], result)
开发者ID:abhinav-upadhyay,项目名称:tensorflow,代码行数:9,代码来源:segment_reduction_ops_test.py


示例11: testSegmentIdsSize

 def testSegmentIdsSize(self):
   shape = [4, 4]
   for use_gpu in [True, False]:
     with self.cached_session(use_gpu=use_gpu):
       tf_x, _ = self._input(shape)
       indices = [0, 1]
       s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
       with self.assertRaisesOpError("segment_ids should be the same size"):
         s.eval()
开发者ID:abhinav-upadhyay,项目名称:tensorflow,代码行数:9,代码来源:segment_reduction_ops_test.py


示例12: testSegmentIdsHole

 def testSegmentIdsHole(self):
   shape = [4, 4]
   with self.test_session():
     tf_x, np_x = self._input(shape)
     indices = [0, 0, 3, 3]
     np_ans = self._segmentReduce(indices, np_x, np.add)
     s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
     tf_ans = s.eval()
     self.assertAllClose(np_ans, tf_ans)
开发者ID:AlbertXiebnu,项目名称:tensorflow,代码行数:9,代码来源:segment_reduction_ops_test.py


示例13: _SegmentMeanGrad

def _SegmentMeanGrad(op, grad):
    """Gradient for SegmentMean."""
    input_rank = array_ops.rank(op.inputs[0])
    ones_shape = array_ops.concat(
        0, [array_ops.shape(op.inputs[1]), array_ops.fill(array_ops.expand_dims(input_rank - 1, 0), 1)]
    )
    ones = array_ops.fill(ones_shape, constant_op.constant(1, dtype=grad.dtype))
    scaled_grad = grad * math_ops.inv(math_ops.segment_sum(ones, op.inputs[1]))
    return array_ops.gather(scaled_grad, op.inputs[1]), None
开发者ID:ChanningPing,项目名称:tensorflow,代码行数:9,代码来源:math_grad.py


示例14: testSegmentIdsHole

 def testSegmentIdsHole(self):
   shape = [4, 4]
   for use_gpu in [True, False]:
     with self.cached_session(use_gpu=use_gpu):
       tf_x, np_x = self._input(shape, dtype=dtypes_lib.float32)
       indices = [0, 0, 3, 3]
       np_ans = self._segmentReduce(indices, np_x, np.add)
       s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
       tf_ans = s.eval()
       self.assertAllClose(np_ans, tf_ans)
开发者ID:abhinav-upadhyay,项目名称:tensorflow,代码行数:10,代码来源:segment_reduction_ops_test.py


示例15: testSegmentIdsInvalid3

 def testSegmentIdsInvalid3(self):
   shape = [4, 4]
   with self.cached_session():
     tf_x, _ = self._input(shape)
     indices = [0, 1, 2, 0]
     s = math_ops.segment_sum(data=tf_x, segment_ids=indices)
     with self.assertRaisesOpError(
         r"Segment id 1 out of range \[0, 1\), possibly "
         "because 'segment_ids' input is not sorted."):
       s.eval()
开发者ID:abhinav-upadhyay,项目名称:tensorflow,代码行数:10,代码来源:segment_reduction_ops_test.py


示例16: _SegmentMinOrMaxGrad

def _SegmentMinOrMaxGrad(op, grad):
  """ Gradient for SegmentMin and SegmentMax. """
  zeros = array_ops.zeros_like(op.inputs[0], dtype=op.inputs[0].dtype)
  # Get the number of selected (minimum or maximum) elements in each segment.
  gathered_outputs = array_ops.gather(op.outputs[0], op.inputs[1])
  is_selected = math_ops.equal(op.inputs[0], gathered_outputs)
  num_selected = math_ops.segment_sum(math_ops.cast(is_selected, grad.dtype),
                                      op.inputs[1])
  # Compute the gradient for each segment. The gradient for the ith segment is
  # divided evenly among the selected elements in that segment.
  weighted_grads = math_ops.div(grad, num_selected)
  gathered_grads = array_ops.gather(weighted_grads, op.inputs[1])
  return array_ops.where(is_selected, gathered_grads, zeros), None
开发者ID:neuroradiology,项目名称:tensorflow,代码行数:13,代码来源:math_grad.py


示例17: _linear_predictions

    def _linear_predictions(self, examples):
        """Returns predictions of the form w*x."""
        with name_scope("sdca/prediction"):
            sparse_variables = self._convert_n_to_tensor(self._variables["sparse_features_weights"])
            result = 0.0
            for sfc, sv in zip(examples["sparse_features"], sparse_variables):
                # TODO(sibyl-Aix6ihai): following does not take care of missing features.
                result += math_ops.segment_sum(
                    math_ops.mul(array_ops.gather(sv, sfc.feature_indices), sfc.feature_values), sfc.example_indices
                )
            dense_features = self._convert_n_to_tensor(examples["dense_features"])
            dense_variables = self._convert_n_to_tensor(self._variables["dense_features_weights"])

            for i in range(len(dense_variables)):
                result += math_ops.matmul(dense_features[i], array_ops.expand_dims(dense_variables[i], -1))

        # Reshaping to allow shape inference at graph construction time.
        return array_ops.reshape(result, [-1])
开发者ID:apollos,项目名称:tensorflow,代码行数:18,代码来源:sdca_ops.py


示例18: _linear_predictions

 def _linear_predictions(self, examples):
   """Returns predictions of the form w*x."""
   with name_scope('sdca/prediction'):
     sparse_variables = self._convert_n_to_tensor(self._variables[
         'sparse_features_weights'])
     predictions = 0
     for st_i, sv in zip(examples['sparse_features'], sparse_variables):
       ei, fi = array_ops.split(1, 2, st_i.indices)
       ei = array_ops.reshape(ei, [-1])
       fi = array_ops.reshape(fi, [-1])
       fv = array_ops.reshape(st_i.values, [-1])
       # TODO(rohananil): This does not work if examples have empty features.
       predictions += math_ops.segment_sum(
           math_ops.mul(
               array_ops.gather(sv, fi), fv), array_ops.reshape(ei, [-1]))
     dense_features = self._convert_n_to_tensor(examples['dense_features'])
     dense_variables = self._convert_n_to_tensor(self._variables[
         'dense_features_weights'])
     for i in range(len(dense_variables)):
       predictions += dense_features[i] * dense_variables[i]
   return predictions
开发者ID:CPostelnicu,项目名称:tensorflow,代码行数:21,代码来源:sdca_ops.py


示例19: _logits

 def _logits(self, examples):
   """Compute logits for each example."""
   with name_scope('logits'):
     sparse_variables = self._convert_n_to_tensor(self._variables[
         'sparse_features_weights'])
     logits = 0
     for st_i, sv in zip(examples['sparse_features'], sparse_variables):
       ei, fi = array_ops.split(1, 2, st_i.indices)
       ei = array_ops.reshape(ei, [-1])
       fi = array_ops.reshape(fi, [-1])
       fv = array_ops.reshape(st_i.values, [-1])
       # TODO(rohananil): This does not work if examples have empty features.
       logits += math_ops.segment_sum(
           math_ops.mul(
               array_ops.gather(sv, fi), fv), array_ops.reshape(ei, [-1]))
     dense_features = self._convert_n_to_tensor(examples['dense_features'])
     dense_variables = self._convert_n_to_tensor(self._variables[
         'dense_features_weights'])
     for i in xrange(len(dense_variables)):
       logits += dense_features[i] * dense_variables[i]
     return logits
开发者ID:Avik0186,项目名称:tensorflow,代码行数:21,代码来源:sdca_ops.py


示例20: _linear_predictions

  def _linear_predictions(self, examples):
    """Returns predictions of the form w*x."""
    with name_scope('sdca/prediction'):
      sparse_variables = self._convert_n_to_tensor(self._variables[
          'sparse_features_weights'])
      result = 0.0
      for st_i, sv in zip(examples['sparse_features'], sparse_variables):
        ei, fi = array_ops.split(1, 2, st_i.indices)
        ei = array_ops.reshape(ei, [-1])
        fi = array_ops.reshape(fi, [-1])
        fv = array_ops.reshape(st_i.values, [-1])
        # TODO(sibyl-Aix6ihai): This does not work if examples have empty features.
        result += math_ops.segment_sum(
            math_ops.mul(array_ops.gather(sv, fi), fv), ei)
      dense_features = self._convert_n_to_tensor(examples['dense_features'])
      dense_variables = self._convert_n_to_tensor(self._variables[
          'dense_features_weights'])

      for i in range(len(dense_variables)):
        result += dense_features[i] * dense_variables[i]

    # Reshaping to allow shape inference at graph construction time.
    return array_ops.reshape(result, [-1])
开发者ID:4chin,项目名称:tensorflow,代码行数:23,代码来源:sdca_ops.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python math_ops.select函数代码示例发布时间:2022-05-27
下一篇:
Python math_ops.scalar_mul函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap