在 Tensorflow 中将矩阵的严格上三角部分转换为数组 [英] Convert the strictly upper triangular part of a matrix into an array in Tensorflow

查看:51
本文介绍了在 Tensorflow 中将矩阵的严格上三角部分转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was trying to convert the strictly upper triangular part of a matrix into an array in Tensorflow. Here is an example:

输入:

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

输出:

[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)

谢谢!

推荐答案

我终于想出了如何使用 Tensorflow 做到这一点.

I finally figured out how to do that using Tensorflow.

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

The idea is to define a placeholder as the boolean mask and then use numpy to pass a boolean matrix to the boolean mask in the runtime. I share 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}))

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

My Python version is 3.6 and my Tensorflow version is 0.12.0rc1. The output of the above code is

[2, 3, 6]

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

This method can be further generalized. We can use numpy to construct any kind of mask and then pass the mask to the Tensorflow to extract the part of the tensor of interest.

这篇关于在 Tensorflow 中将矩阵的严格上三角部分转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆