I am new in Python and Tensorflow and I am working on a project in Python. Assume I have vector X,
X=[x1,x2,x3]
and want to convert it to a lower triangular matrix A with one in the main diagonal,
A=[ [ 1, 0, 0] , [ x1, 1, 0], [ x2, x3, 1] ].
In R I used this simple code:
A<-diag(3)
A[lower.tri(A)] <- X.
In my project, X is a tensor, as the output of a Neural network in Tensorflow.
X <- layer_dense(hidden layer, dec_dim)
So, I want to do that in Keras or Tensorflow same as before if it is possible. For example in Keras,
from keras import backend as K
A= K.eye(3)
But I could not find a solution in Tensorflow or Keras for the second command. I would not like to use the For loop here because of the running time. Is there any short solution for that? Do you have any idea about that? Thanks beforehand.
You need to get all indices for X and apply them to A.
from keras import backend as K
import tensorflow as tf
n = 3
X = tf.constant([1,2,3],tf.float32)
A = K.eye(n)
column,row = tf.meshgrid(tf.range(n),tf.range(n))
indices = tf.where(tf.less(column,row))
# [[1 0]
# [2 0]
# [2 1]]
A = tf.scatter_nd(indices,X,(n,n)) + A
# if your lower triangular part of A not equal 0, you can use follow code.
# tf.matrix_band_part(A, 0, -1)==> Upper triangular part
# A = tf.scatter_nd(indices,X,(n,n)) + tf.matrix_band_part(A, 0, -1)
print(K.eval(A))
# [[1. 0. 0.]
# [1. 1. 0.]
# [2. 3. 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