Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate identity tensor with python?

I know about np.eye which generates identity matrix. I mean the identity matrix as

In linear algebra, the identity matrix, or sometimes ambiguously called a unit matrix, of size n is the n × n square matrix with ones on the main diagonal and zeros elsewhere.

And I know that we can create it in Numpy with np.identity(3).

But, I would like to know how can I have an identity Tensor in python.

I would like to use identity tensor in tensors multiplication. Like below:

where G = Er ×1 U1 ×2 U2 ...×M UM is a transformation tensor, and Er ∈ R r×r×...×r is an identity tensor (the diagonal elements are 1, and all other entries are 0). I need to have the code for generating the identity tensor.

Thank you in advance.

like image 861
Masoud Erfani Avatar asked Sep 13 '25 22:09

Masoud Erfani


2 Answers

Something like this?

def nd_id(n, d):
    out = np.zeros( (n,) * d )
    out[ tuple([np.arange(n)] * d) ] = 1
    return out

Testing

nd_id(3,3)
Out[]: 
array([[[ 1.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  1.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  1.]]])
like image 63
Daniel F Avatar answered Sep 15 '25 10:09

Daniel F


Instead of np.identity use tf.eye:

tf.eye(2)
# [[1., 0.],
#  [0., 1.]]
like image 27
gorjan Avatar answered Sep 15 '25 12:09

gorjan