Convert strictly the upper triangular part of the matrix to an array in Tensorflow

I tried to convert the strictly upper triangular part of the matrix to an array in Tensorflow. Here is an example:

Input:

[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]

Conclusion:

[2, 3, 6]

I tried the following code, but it did not work (an error was reported):

def upper_triangular_to_array(A):
    mask = tf.matrix_band_part(tf.ones_like(A, dtype=tf.bool), 0, -1)
    return tf.boolean_mask(A, mask)

Thank!

+4
source share
3 answers

I finally figured out how to do this using Tensorflow.

The idea is to define a placeholder as a Boolean mask, and then use numpy to pass the Boolean matrix to the Boolean mask at runtime. I am sharing my code below:

import tensorflow as tf
import numpy as np

# The matrix has size n-by-n
n = 3
# define a boolean mask as a placeholder
mask = tf.placeholder(tf.bool, shape=(n, n))
# A is the matrix
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    npmask = np.triu(np.ones((n, n), dtype=np.bool_), 1)
    A_upper_triangular = tf.boolean_mask(A, mask)
    print(sess.run(A_upper_triangular, feed_dict={mask: npmask}))

My Python version is 3.6, and my Tensorflow version is 0.12.0rc1. Output above code

[2, 3, 6]

. numpy Tensorflow, .

0

@Cech_Cohomology, Numpy , TensorFlow.

import tensorflow as tf

# The matrix has size n-by-n
n = 3

# A is the matrix
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

ones = tf.ones_like(A)
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.cast(mask_a - mask_b, dtype=tf.bool) # Make a bool mask

upper_triangular_flat = tf.boolean_mask(A, mask)

sess = tf.Session()
print(sess.run(upper_triangular_flat))

:

[2 3 6]

, feed_dict.

+3

python 2.7, NxN- :

def upper_triangular_to_array(A):
    N = A.shape[0]
    return np.array([p for i, p in enumerate(A.flatten()) if i > (i / N) * (1 + N)])

, numpy, . , , python 3.x

-1
source

Source: https://habr.com/ru/post/1666048/


All Articles