diag_embed

paddle.fluid.layers.diag_embed(input, offset=0, dim1=-2, dim2=-1)[source]

This OP creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2) are filled by input. By default, a 2D plane formed by the last two dimensions of the returned tensor will be selected.

The argument offset determines which diagonal is generated:

  • If offset = 0, it is the main diagonal.

  • If offset > 0, it is above the main diagonal.

  • If offset < 0, it is below the main diagonal.

Parameters
  • input (Variable|numpy.ndarray) – The input tensor. Must be at least 1-dimensional. The input data type should be float32, float64, int32, int64.

  • offset (int, optional) – Which diagonal to consider. Default: 0 (main diagonal).

  • dim1 (int, optional) – The first dimension with respect to which to take diagonal. Default: -2.

  • dim2 (int, optional) – The second dimension with respect to which to take diagonal. Default: -1.

Returns

Variable, the output data type is the same as input data type.

Examples

import paddle.fluid as fluid
import paddle.fluid.dygraph as dg
import numpy as np

diag_embed = np.random.randn(2, 3).astype('float32')
# [[ 0.7545889 , -0.25074545,  0.5929117 ],
#  [-0.6097662 , -0.01753256,  0.619769  ]]
with dg.guard():
    data1 = fluid.layers.diag_embed(diag_embed)
    data1.numpy()
    # [[[ 0.7545889 ,  0.        ,  0.        ],
    #  [ 0.        , -0.25074545,  0.        ],
    #   [ 0.        ,  0.        ,  0.5929117 ]],

    # [[-0.6097662 ,  0.        ,  0.        ],
    #  [ 0.        , -0.01753256,  0.        ],
    #  [ 0.        ,  0.        ,  0.619769  ]]]

    data2 = fluid.layers.diag_embed(diag_embed, offset=-1, dim1=0, dim2=2)
    data2.numpy()
    # [[[ 0.        ,  0.        ,  0.        ,  0.        ],
    #   [ 0.7545889 ,  0.        ,  0.        ,  0.        ],
    #   [ 0.        , -0.25074545,  0.        ,  0.        ],
    #   [ 0.        ,  0.        ,  0.5929117 ,  0.        ]],
    #
    #  [[ 0.        ,  0.        ,  0.        ,  0.        ],
    #   [-0.6097662 ,  0.        ,  0.        ,  0.        ],
    #   [ 0.        , -0.01753256,  0.        ,  0.        ],
    #   [ 0.        ,  0.        ,  0.619769  ,  0.        ]]]

    data3 = fluid.layers.diag_embed(diag_embed, offset=1, dim1=0, dim2=2)
    data3.numpy()
    # [[[ 0.        ,  0.7545889 ,  0.        ,  0.        ],
    #   [ 0.        , -0.6097662 ,  0.        ,  0.        ]],
    #
    #  [[ 0.        ,  0.        , -0.25074545,  0.        ],
    #   [ 0.        ,  0.        , -0.01753256,  0.        ]],
    #
    #  [[ 0.        ,  0.        ,  0.        ,  0.5929117 ],
    #   [ 0.        ,  0.        ,  0.        ,  0.619769  ]],
    #
    #  [[ 0.        ,  0.        ,  0.        ,  0.        ],
    #   [ 0.        ,  0.        ,  0.        ,  0.        ]]]