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


Python math_ops.less函数代码示例

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


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

示例1: testAssertDivideByZero

 def testAssertDivideByZero(self):
   with self.test_session() as sess:
     epsilon = ops.convert_to_tensor(1e-20)
     x = ops.convert_to_tensor(0.0)
     y = ops.convert_to_tensor(1.0)
     z = ops.convert_to_tensor(2.0)
     # assert(epsilon < y)
     # z / y
     with sess.graph.control_dependencies([
         control_flow_ops.Assert(
             math_ops.less(epsilon, y), ["Divide-by-zero"])
     ]):
       out = math_ops.div(z, y)
     self.assertAllEqual(2.0, out.eval())
     # assert(epsilon < x)
     # z / x
     #
     # This tests printing out multiple tensors
     with sess.graph.control_dependencies([
         control_flow_ops.Assert(
             math_ops.less(epsilon, x), ["Divide-by-zero", "less than x"])
     ]):
       out = math_ops.div(z, x)
     with self.assertRaisesOpError("less than x"):
       out.eval()
开发者ID:1000sprites,项目名称:tensorflow,代码行数:25,代码来源:logging_ops_test.py

示例2: _nest_where

 def _nest_where(vals, cases):
   assert len(vals) == len(cases) - 1
   if len(vals) == 1:
     return array_ops.where(
         math_ops.less(l1_norm, const(vals[0])), cases[0], cases[1])
   else:
     return array_ops.where(
         math_ops.less(l1_norm, const(vals[0])), cases[0],
         _nest_where(vals[1:], cases[1:]))
开发者ID:Wajih-O,项目名称:tensorflow,代码行数:9,代码来源:linalg_impl.py

示例3: testCorrectlyPicksVector

 def testCorrectlyPicksVector(self):
   with self.cached_session():
     x = np.arange(10, 12)
     y = np.arange(15, 18)
     self.assertAllEqual(
         x, self.evaluate(du.pick_vector(math_ops.less(0, 5), x, y)))
     self.assertAllEqual(
         y, self.evaluate(du.pick_vector(math_ops.less(5, 0), x, y)))
     self.assertAllEqual(x,
                         du.pick_vector(
                             constant_op.constant(True), x, y))  # No eval.
     self.assertAllEqual(y,
                         du.pick_vector(
                             constant_op.constant(False), x, y))  # No eval.
开发者ID:Wajih-O,项目名称:tensorflow,代码行数:14,代码来源:util_test.py

示例4: setUpClass

    def setUpClass(cls):
        cls._dump_root = tempfile.mkdtemp()

        with session.Session() as sess:
            loop_var = constant_op.constant(0, name="while_loop_test/loop_var")
            cond = lambda loop_var: math_ops.less(loop_var, 10)
            body = lambda loop_var: math_ops.add(loop_var, 1)
            while_loop = control_flow_ops.while_loop(cond, body, [loop_var], parallel_iterations=1)

            run_options = config_pb2.RunOptions(output_partition_graphs=True)
            debug_url = "file://%s" % cls._dump_root

            watch_opts = run_options.debug_tensor_watch_opts

            # Add debug tensor watch for "while/Identity".
            watch = watch_opts.add()
            watch.node_name = "while/Identity"
            watch.output_slot = 0
            watch.debug_ops.append("DebugIdentity")
            watch.debug_urls.append(debug_url)

            # Invoke Session.run().
            run_metadata = config_pb2.RunMetadata()
            sess.run(while_loop, options=run_options, run_metadata=run_metadata)

        cls._debug_dump = debug_data.DebugDumpDir(cls._dump_root, partition_graphs=run_metadata.partition_graphs)

        cls._analyzer = analyzer_cli.DebugAnalyzer(cls._debug_dump)
        cls._registry = debugger_cli_common.CommandHandlerRegistry()
        cls._registry.register_command_handler(
            "list_tensors", cls._analyzer.list_tensors, cls._analyzer.get_help("list_tensors"), prefix_aliases=["lt"]
        )
        cls._registry.register_command_handler(
            "print_tensor", cls._analyzer.print_tensor, cls._analyzer.get_help("print_tensor"), prefix_aliases=["pt"]
        )
开发者ID:brchiu,项目名称:tensorflow,代码行数:35,代码来源:analyzer_cli_test.py

示例5: random_flip_up_down

def random_flip_up_down(image, seed=None):
  """Randomly flips an image vertically (upside down).

  With a 1 in 2 chance, outputs the contents of `image` flipped along the first
  dimension, which is `height`.  Otherwise output the image as-is.

  Args:
    image: A 3-D tensor of shape `[height, width, channels].`
    seed: A Python integer. Used to create a random seed. See
      [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
      for behavior.

  Returns:
    A 3-D tensor of the same type and shape as `image`.

  Raises:
    ValueError: if the shape of `image` not supported.
  """
  image = ops.convert_to_tensor(image, name='image')
  _Check3DImage(image, require_static=False)
  uniform_random = random_ops.random_uniform([], 0, 1.0, seed=seed)
  mirror_cond = math_ops.less(uniform_random, .5)
  result = control_flow_ops.cond(mirror_cond,
                                 lambda: array_ops.reverse(image, [0]),
                                 lambda: image)
  return fix_image_flip_shape(image, result)
开发者ID:Jackhuang945,项目名称:tensorflow,代码行数:26,代码来源:image_ops_impl.py

示例6: testControlFlow

  def testControlFlow(self):
    with self.cached_session() as sess:
      v0 = variables.Variable(0, name="v0")
      var_dict = {}

      # Call get_variable in each of the cond clauses.
      def var_in_then_clause():
        v1 = variables.Variable(1, name="v1")
        var_dict["v1"] = v1
        return v1 + v0

      def var_in_else_clause():
        v2 = variables.Variable(2, name="v2")
        var_dict["v2"] = v2
        return v2 + v0

      add = control_flow_ops.cond(
          math_ops.less(v0, 10), var_in_then_clause, var_in_else_clause)
      v1 = var_dict["v1"]
      v2 = var_dict["v2"]
      # We should be able to initialize and run v1 and v2 without initializing
      # v0, even if the variable was created with a control dep on v0.
      self.evaluate(v1.initializer)
      self.assertEqual([1], self.evaluate(v1))
      self.evaluate(v2.initializer)
      self.assertEqual([2], self.evaluate(v2))
      # v0 should still be uninitialized.
      with self.assertRaisesRegexp(errors_impl.OpError, "uninitialized"):
        self.evaluate(v0)
      # We should not be able to run 'add' yet.
      with self.assertRaisesRegexp(errors_impl.OpError, "uninitialized"):
        self.evaluate(add)
      # If we initialize v0 we should be able to run 'add'.
      self.evaluate(v0.initializer)
      self.evaluate(add)
开发者ID:adit-chandra,项目名称:tensorflow,代码行数:35,代码来源:variables_test.py

示例7: is_strictly_increasing

def is_strictly_increasing(x, name=None):
    """Returns `True` if `x` is strictly increasing.

  Elements of `x` are compared in row-major order.  The tensor `[x[0],...]`
  is strictly increasing if for every adjacent pair we have `x[i] < x[i+1]`.
  If `x` has less than two elements, it is trivially strictly increasing.

  See also:  `is_non_decreasing`

  Args:
    x: Numeric `Tensor`.
    name: A name for this operation (optional).
      Defaults to "is_strictly_increasing"

  Returns:
    Boolean `Tensor`, equal to `True` iff `x` is strictly increasing.

  Raises:
    TypeError: if `x` is not a numeric tensor.
  """
    with ops.op_scope([x], name, "is_strictly_increasing"):
        diff = _get_diff_for_monotonic_comparison(x)
        # When len(x) = 1, diff = [], less = [], and reduce_all([]) = True.
        zero = ops.convert_to_tensor(0, dtype=diff.dtype)
        return math_ops.reduce_all(math_ops.less(zero, diff))
开发者ID:RChandrasekar,项目名称:tensorflow,代码行数:25,代码来源:check_ops.py

示例8: random_flip_left_right

def random_flip_left_right(image, seed=None):
  """Randomly flip an image horizontally (left to right).

  With a 1 in 2 chance, outputs the contents of `image` flipped along the
  second dimension, which is `width`.  Otherwise output the image as-is.

  Args:
    image: A 3-D tensor of shape `[height, width, channels].`
    seed: A Python integer. Used to create a random seed. See
      [`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
      for behavior.

  Returns:
    A 3-D tensor of the same type and shape as `image`.

  Raises:
    ValueError: if the shape of `image` not supported.
  """
  image = ops.convert_to_tensor(image, name='image')
  _Check3DImage(image, require_static=False)
  uniform_random = random_ops.random_uniform([], 0, 1.0, seed=seed)
  mirror_cond = math_ops.less(uniform_random, .5)
  stride = array_ops.where(mirror_cond, -1, 1)
  result = image[:, ::stride, :]
  return fix_image_flip_shape(image, result)
开发者ID:kdavis-mozilla,项目名称:tensorflow,代码行数:25,代码来源:image_ops_impl.py

示例9: testCorrectlyPicksVector

 def testCorrectlyPicksVector(self):
   with self.test_session():
     x = np.arange(10, 12)
     y = np.arange(15, 18)
     self.assertAllEqual(x,
                         distribution_util.pick_vector(
                             math_ops.less(0, 5), x, y).eval())
     self.assertAllEqual(y,
                         distribution_util.pick_vector(
                             math_ops.less(5, 0), x, y).eval())
     self.assertAllEqual(x,
                         distribution_util.pick_vector(
                             constant_op.constant(True), x, y))  # No eval.
     self.assertAllEqual(y,
                         distribution_util.pick_vector(
                             constant_op.constant(False), x, y))  # No eval.
开发者ID:AlbertXiebnu,项目名称:tensorflow,代码行数:16,代码来源:distribution_util_test.py

示例10: createAndRunGraphWithWhileLoop

  def createAndRunGraphWithWhileLoop(self):
    """Create and run a TensorFlow Graph with a while loop to generate dumps."""

    self.dump_root = self.get_temp_dir()
    self.curr_file_path = os.path.abspath(
        tf_inspect.getfile(tf_inspect.currentframe()))

    # Run a simple TF graph to generate some debug dumps that can be used in
    # source annotation.
    with session.Session() as sess:
      loop_body = lambda i: math_ops.add(i, 2)
      self.traceback_first_line = line_number_above()

      loop_cond = lambda i: math_ops.less(i, 16)

      i = constant_op.constant(10, name="i")
      loop = control_flow_ops.while_loop(loop_cond, loop_body, [i])

      run_options = config_pb2.RunOptions(output_partition_graphs=True)
      debug_utils.watch_graph(
          run_options, sess.graph, debug_urls=["file://%s" % self.dump_root])
      run_metadata = config_pb2.RunMetadata()
      sess.run(loop, options=run_options, run_metadata=run_metadata)

      self.dump = debug_data.DebugDumpDir(
          self.dump_root, partition_graphs=run_metadata.partition_graphs)
      self.dump.set_python_graph(sess.graph)
开发者ID:1000sprites,项目名称:tensorflow,代码行数:27,代码来源:source_utils_test.py

示例11: random_flip_left_right

def random_flip_left_right(image, seed=None):
  """Randomly flip an image horizontally (left to right).

  With a 1 in 2 chance, outputs the contents of `image` flipped along the
  second dimension, which is `width`.  Otherwise output the image as-is.

  Args:
    image: A 3-D tensor of shape `[height, width, channels].`
    seed: A Python integer. Used to create a random seed. See
      @{tf.set_random_seed}
      for behavior.

  Returns:
    A 3-D tensor of the same type and shape as `image`.

  Raises:
    ValueError: if the shape of `image` not supported.
  """
  image = ops.convert_to_tensor(image, name='image')
  _Check3DImage(image, require_static=False)
  uniform_random = random_ops.random_uniform([], 0, 1.0, seed=seed)
  mirror_cond = math_ops.less(uniform_random, .5)
  result = control_flow_ops.cond(mirror_cond,
                                 lambda: array_ops.reverse(image, [1]),
                                 lambda: image)
  return fix_image_flip_shape(image, result)
开发者ID:duzy,项目名称:tensorflow,代码行数:26,代码来源:image_ops_impl.py

示例12: testSelectOp

  def testSelectOp(self):
    if test.is_gpu_available(cuda_only=True):
      random_seed.set_random_seed(0)
      x = random_ops.truncated_normal([1, 784], seed=0)
      conv = _two_layer_model(x)
      add = math_ops.add(conv, conv)
      mean = math_ops.reduce_mean(conv)
      condition = math_ops.less(conv, mean)
      select = gen_math_ops._select(condition, conv, add)
      output = array_ops.identity(select)

      with session.Session() as sess:
        output_val_ref = sess.run(output)

      with session.Session(config=_get_config()) as sess:
        metadata = config_pb2.RunMetadata()
        output_val = sess.run(output, run_metadata=metadata)

      nodes = []
      num_transposes = 0
      for node in metadata.cost_graph.node:
        if _is_transpose(node.name):
          num_transposes += 1
        nodes.append(node.name)

      expected_num_transposes = 2
      self.assertEqual(expected_num_transposes, num_transposes)
      self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
      self._assert_trans_nchw_to_nhwc('Select-0-0', nodes)
      self.assertAllClose(output_val_ref, output_val, atol=1e-3)
开发者ID:ChengYuXiang,项目名称:tensorflow,代码行数:30,代码来源:layout_optimizer_test.py

示例13: testWhileWithScopedAllocator

  def testWhileWithScopedAllocator(self):
    group_size = 2
    group_key = 1
    instance_key0 = 1
    instance_key1 = 2

    config = config_pb2.ConfigProto(device_count={'CPU': group_size})
    rewrite_options = config.graph_options.rewrite_options
    rewrite_options.scoped_allocator_optimization = (
        rewriter_config_pb2.RewriterConfig.ON)
    del rewrite_options.scoped_allocator_opts.enable_op[:]
    rewrite_options.scoped_allocator_opts.enable_op.append('CollectiveReduce')

    with self.session(config=config) as sess:
      run_ops = []
      for i in range(group_size):
        with ops.device('CPU:%d' % i):
          constant = constant_op.constant(0.)
          cond = lambda i: math_ops.less(i, 10.)
          body = lambda i: math_ops.add(i, 1.)
          input0 = control_flow_ops.while_loop(cond, body, [constant])
          input1 = math_ops.add(constant, 5)
          colred0 = collective_ops.all_reduce(input0, group_size, group_key,
                                              instance_key0, 'Add', 'Id')
          colred1 = collective_ops.all_reduce(input1, group_size, group_key,
                                              instance_key1, 'Add', 'Id')
          run_ops.append(math_ops.add_n([colred0, colred1]))
      results = sess.run(run_ops)
      self.assertEqual(results, [30., 30.])
开发者ID:aritratony,项目名称:tensorflow,代码行数:29,代码来源:collective_ops_test.py

示例14: testWhileLoopWithSingleVariable

  def testWhileLoopWithSingleVariable(self):
    i = constant_op.constant(0)
    c = lambda i: math_ops.less(i, 10)
    b = lambda i: math_ops.add(i, 1)
    r = control_flow_ops.while_loop(c, b, [i])

    self.assertEqual(self.evaluate(r), 10)
开发者ID:bunbutter,项目名称:tensorflow,代码行数:7,代码来源:control_flow_ops_test.py

示例15: _Solve

def _Solve(a, b, c):
    """Return solution of a quadratic minimization.

  The optimization equation is:
       f(a, b, c) = argmin_w{1/2 * a * w^2 + b * w + c * |w|}
  we get optimal solution w*:
       w* = -(b - sign(b)*c)/a if |b| > c else w* = 0

  REQUIRES: Dimensionality of a and b must be same

  Args:
    a: A Tensor
    b: A Tensor
    c: A Tensor with one element.

  Returns:
    A Tensor w, which is solution for the equation
  """
    with ops.name_scope("solve_" + b.op.name):
        c = ops.convert_to_tensor(c)
        k = array_ops.fill(array_ops.shape(b), c)
        zero_t = array_ops.zeros(array_ops.shape(b), dtype=b.dtype)
        w = (c * math_ops.sign(b) - b) / a
        w = math_ops.select(math_ops.less(math_ops.abs(b), k), zero_t, w)
        return w
开发者ID:sherrym,项目名称:tensorflow,代码行数:25,代码来源:ftrl.py


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