我需要张量流中的k-by-k对称矩阵,其中对角线是常数1,非对角线条目是可变的。
即:
k = 3
a = tf.Variable(1.0*tf.ones([k*(k-1)/2, 1]))
然后:
Rho =
[[1, a[0], a[1]],
[[a[0], 1, a[2]],
[[a[1], a[2], 1]]
是否有一些直接的tensorflow实现让我从k
和a
到Rho
?解决相关矩阵是很常见的,所以我怀疑在tf中应该存在直接的实现。
谢谢!
一项提案
遵循k=3
的上述逻辑,从U
获得严格上三角矩阵a
就足够了,然后Rho
就是:< / p>
U = tf.[strictly_upper_triangular](a)
Rho = tf.eye(k) + U + tf.transpose(U)
是否有[strictly_upper_triangular]
这样的功能?
答案 0 :(得分:1)
这是一种可能性:
import tensorflow as tf
import numpy as np
k = 5
# Using a constant instead now for testing
#a = tf.Variable(1.0 * tf.ones([(k * (k - 1)) // 2, 1]))
a = 10 * tf.range((k * (k - 1)) // 2, dtype=tf.float32) + 10
# Make indices and mask
idx = np.zeros((k, k), dtype=int)
mask = np.zeros((k, k), dtype=bool)
triu_idx = np.triu_indices(k, 1)
idx[triu_idx] = np.arange((k * (k - 1)) // 2)
mask[triu_idx] = True
# Make upper triangular matrix
u = tf.where(mask, tf.gather(a, idx), tf.zeros((k, k), dtype=a.dtype))
# Final matrix
Rho = tf.eye(k, dtype=u.dtype) + u + tf.transpose(u)
print(sess.run(Rho))
输出:
[[ 1. 10. 20. 30. 40.]
[ 10. 1. 50. 60. 70.]
[ 20. 50. 1. 80. 90.]
[ 30. 60. 80. 1. 100.]
[ 40. 70. 90. 100. 1.]]
缺点是必须在图形构造时知道k
,因为索引和掩码矩阵是用NumPy构造的。