将矩阵的严格上三角形部分转换为Tensorflow中的数组

Cec*_*ogy 6 python tensorflow

我试图将矩阵的严格上三角形部分转换为Tensorflow中的数组.这是一个例子:

输入:

[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

输出:

[2, 3, 6]
Run Code Online (Sandbox Code Playgroud)

我尝试了以下代码,但它不起作用(报告错误):

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)
Run Code Online (Sandbox Code Playgroud)

谢谢!

小智 8

以下答案紧跟@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))
Run Code Online (Sandbox Code Playgroud)

这输出:

[2 3 6]
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是,当运行图形时,不需要给出一个feed_dict.


Cec*_*ogy 2

我终于弄清楚如何使用 Tensorflow 来做到这一点。

这个想法是定义一个占位符作为布尔掩码,然后使用 numpy 在运行时将布尔矩阵传递给布尔掩码。我在下面分享我的代码:

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}))
Run Code Online (Sandbox Code Playgroud)

我的Python版本是3.6,我的Tensorflow版本是0.12.0rc1。上述代码的输出是

[2, 3, 6]
Run Code Online (Sandbox Code Playgroud)

该方法可以进一步推广。我们可以使用 numpy 构造任何类型的掩码,然后将掩码传递给 Tensorflow 以提取感兴趣的张量部分。