我试图将矩阵的严格上三角形部分转换为Tensorflow中的数组.这是一个例子:
输入:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
输出:
[2, 3, 6]
我尝试了以下代码,但它不起作用(报告错误):
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)
谢谢!
最佳答案:
以下答案紧跟@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.
原文地址:https://codeday.me/bug/20190516/1114456.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。