Tensorflow源码分析--tf.abs()

Tensorflow源码分析–tf.abs()

标签(空格分隔): Tensorflow


tf.abs()

import tensorflow as tf
x = tf.constant([[-2.25 + 4.75j], [-3.25 + 5.75j]])
sess = tf.Session()
print(sess.run(tf.abs(x)))

>>>[[5.25594901]
 [6.60492241]]

该函数源码:

路径:tensorflow-master\tensorflow\python\ops\math_ops.py

  with ops.name_scope(name, "Abs", [x]) as name:
    if isinstance(x, sparse_tensor.SparseTensor):
    #首先判断输入是不是系数矩阵
      if x.values.dtype.is_complex:
        x_abs = gen_math_ops.complex_abs(
            x.values, Tout=x.values.dtype.real_dtype, name=name)
        return sparse_tensor.SparseTensor(
            indices=x.indices, values=x_abs, dense_shape=x.dense_shape)
      x_abs = gen_math_ops._abs(x.values, name=name)
      return sparse_tensor.SparseTensor(
          indices=x.indices, values=x_abs, dense_shape=x.dense_shape)
    else:
      x = ops.convert_to_tensor(x, name="x")
      if x.dtype.is_complex:
      #这里判断输入是否是复数
        return gen_math_ops.complex_abs(x, Tout=x.dtype.real_dtype, name=name)
    #如果不是复数,则按照下面输出
      return gen_math_ops._abs(x, name=name)

该函数原文解释

r"""Computes the absolute value of a tensor.

  Given a tensor `x` of complex numbers, this operation returns a tensor of type
  `float32` or `float64` that is the absolute value of each element in `x`. All
  elements in `x` must be complex numbers of the form \\(a + bj\\). The
  absolute value is computed as \\( \sqrt{a^2 + b^2}\\).  For example:
  ```python
  x = tf.constant([[-2.25 + 4.75j], [-3.25 + 5.75j]])
  tf.abs(x)  # [5.25594902, 6.60492229]
  ```

  Args:
    x: A `Tensor` or `SparseTensor` of type `float16`, `float32`, `float64`,
      `int32`, `int64`, `complex64` or `complex128`.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` or `SparseTensor` the same size and type as `x` with absolute
      values.
    Note, for `complex64` or `complex128` input, the returned `Tensor` will be
      of type `float32` or `float64`, respectively.
  """

猜你喜欢

转载自blog.csdn.net/jiangzhenkang/article/details/80708076
ABS