Tensorflow transpose code analysis

 

1. TF usage
https://github.com/tensorflow/tensorflow/blob/r1.14/tensorflow/python/ops/array_ops.py#L1651-L1739 1594
1.1 Introduction

transpose
 @compatibility(numpy)
  In `numpy` transposes are memory-efficient constant time operations as they
  simply return a new view of the same data with adjusted `strides`.
  TensorFlow does not support strides, so `transpose` returns a new tensor with
  the items permuted.
  @end_compatibility
  
  Args:
    a: A `Tensor`.
    perm: A permutation of the dimensions of `a`.
    name: A name for the operation (optional).
    conjugate: Optional bool. Setting it to `True` is mathematically equivalent
      to tf.math.conj(tf.transpose(input)).
  Returns:
    A transposed `Tensor`.
    
    
1.2 Code
  """
  with ops.name_scope(name, "transpose", [a]) as name:
    transpose_fn = (
        gen_array_ops.conjugate_transpose if
        (conjugate and a.dtype.is_complex) else gen_array_ops.transpose)
    if perm is None:
      a = ops.convert_to_tensor(a, name="a")
      if not a.get_shape().ndims:
        rank = gen_array_ops.rank(a)
        perm = (rank - 1) - gen_math_ops._range(0, rank, 1)
      else:
        rank = a.get_shape().ndims
        perm = (rank - 1) - np.arange(rank)
      ret = transpose_fn(a, perm, name=name)
      # NOTE(mrry): Setting the shape explicitly because
      #   reverse is not handled by the shape function.
      if not context.executing_eagerly():
        input_shape = ret.op.inputs[0].get_shape().dims
        if input_shape is not None:
          ret.set_shape(input_shape[::-1])
    else:
      ret = transpose_fn(a, perm, name=name)
    return ret
    
    
3. Usage tips    
we can see that transpose_fn is the core function.

    Line 29: // This file has two implementations of Transpose.
    Line 55:                        "Transpose op permutations array is out of bounds.");
    Line 76:                      "Transpose op only supports 1D-4D input arrays.");
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章