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 then × 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.
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.]]])
Instead of np.identity
use tf.eye
:
tf.eye(2)
# [[1., 0.],
# [0., 1.]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With