Taby
Taby

Reputation: 85

Transform an array into a matrix with its elements filling the upper triangle of matrix in Tensorflow

I want to convert array into matrix filling the upper triangle of matrix in one of the following manners

array to matrix

In tf.contrib.distributions.fill_triangular, the triangular matrix elements are filled in a clockwise spiral, including the diagonal elements. I tried following set of commands, but it didn’t work.

x = placeholder(tf.float32, shape=[None, 891])
dummy_expected_output = placeholder(tf.float32, shape=[None, 42, 42])
ones = tf.ones_like(dummy_expected_output) #size of the output matrix 
mask_a = tf.matrix_band_part(ones, 0, -1)  # Upper triangular matrix of 0s and 1s
mask_b = tf.matrix_band_part(ones, 0, 0)  # Diagonal matrix of 0s and 1s
mask = tf.subtract(mask_a, mask_b) # Mask of upper triangle above diagonal
zero = tf.constant(0, dtype=tf.float32)
non_zero = tf.not_equal(ones, zero) #Conversion of mask to Boolean matrix

indices = tf.cast(tf.where(non_zero),dtype=tf.int64) # Extracting the indices of upper triangle elements

zeros = tf.zeros_like(dummy_expected_output) #size of the output matrix
out = tf.add(zeros, tf.sparse_to_dense(indices,tf.cast(tf.shape(zeros),dtype=tf.int64), tf.reshape(x,[-1]), default_value=0))

It results in error “Failed to convert object of type to Tensor. Contents: [None]. Consider casting elements to a supported type”. I tried casting but it didn’t work. Can anyone help me please?

Upvotes: 2

Views: 837

Answers (1)

Mohan Radhakrishnan
Mohan Radhakrishnan

Reputation: 3197

One of your output patterns is obtained by slightly refactoring your code.

sess = tf.InteractiveSession()
x = tf.constant([1, 2, 3, 4, 5, 6])
ones = tf.ones((4,4),dtype=tf.int64) #size of the output matrix
mask_a = tf.matrix_band_part(ones, 0, -1)  # Upper triangular matrix of 0s and 1s
mask_b = tf.matrix_band_part(ones, 0, 0)  # Diagonal matrix of 0s and 1s
mask = tf.subtract(mask_a, mask_b) # Mask of upper triangle above diagonal

zero = tf.constant(0, dtype=tf.int64)
non_zero = tf.not_equal(mask, zero) #Conversion of mask to Boolean matrix
sess.run(non_zero)
indices = tf.where(non_zero) # Extracting the indices of upper trainagle elements

out = tf.SparseTensor(indices,x,dense_shape=tf.cast((4,4),dtype=tf.int64))
dense = tf.sparse_tensor_to_dense(out)
dense = tf.print(dense, [dense], summarize=100)
sess.run(dense)

Output is this.

[[0 1 2 3]
 [0 0 4 5]
 [0 0 0 6]
 [0 0 0 0]]

enter image description here

Upvotes: 2

Related Questions