问题描述
我想将形状为(..., n * (n - 1) / 2)
的数组压缩到形状为(..., n, n)
的张量的下三角部分,其中...
表示任意形状.在numpy中,我将其实现为
I would like to pack an array of shape (..., n * (n - 1) / 2)
into the lower triangular part of a tensor with shape (..., n, n)
where ...
denotes an arbitrary shape. In numpy, I would implement it as
import numpy as np
# Create the array to store data in
arbitrary_shape = (10, 11, 12)
n = 5
target = np.zeros(arbitrary_shape + (n, n))
# Create the source array
source = np.random.normal(0, 1, arbitrary_shape + (n * (n - 1) / 2,))
# Create indices and set values
u, v = np.tril_indices(n, -1)
target[..., u, v] = source
# Check that everything went ok
print target[0, 0, 0]
到目前为止,使用transpose
,reshape
和scatter_update
的组合,我已经能够在张量流中实现类似的功能,但是感觉很笨拙.
So far, I've been able to achieve something similar in tensorflow using a combination of transpose
, reshape
and scatter_update
but it feels clumsy.
import tensorflow as tf
# Create the source array
source = np.random.normal(0, 1, (n * (n - 1) / 2,) + arbitrary_shape)
sess = tf.InteractiveSession()
# Create a flattened representation
target = tf.Variable(np.zeros((n * n,) + arbitrary_shape))
# Assign the values
target = tf.scatter_update(target, u * n + v, source)
# Reorder the axes and reshape into a square matrix along the last dimension
target = tf.transpose(target, (1, 2, 3, 0))
target = tf.reshape(target, arbitrary_shape + (n, n))
# Initialise variables and check results
sess.run(tf.initialize_all_variables())
print target.eval()[0, 0, 0]
sess.close()
有没有更好的方法来实现这一目标?
Is there a better way to achieve this?
推荐答案
我意识到这有点晚了,但是我一直在尝试加载一个较低的三角矩阵,并且我使用sparse_to_dense使其工作:
I realise this is a bit late, but I've been attempting to load a lower triangular matrix, and I got it working using sparse_to_dense:
import tensorflow as tf
import numpy as np
session = tf.InteractiveSession()
n = 4 # Number of dimensions of matrix
# Get pairs of indices of positions
indices = list(zip(*np.tril_indices(n)))
indices = tf.constant([list(i) for i in indices], dtype=tf.int64)
# Test values to load into matrix
test = tf.constant(np.random.normal(0, 1, int(n*(n+1)/2)), dtype=tf.float64)
# Can pass in list of values and indices to tf.sparse_to_dense
# and it will return a dense matrix
dense = tf.sparse_to_dense(sparse_indices=indices, output_shape=[n, n], \
sparse_values=test, default_value=0, \
validate_indices=True)
sess.close()
这篇关于将数组打包到张量的下三角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!