Skip to content Skip to sidebar Skip to footer

Packing Array Into Lower Triangular Of A Tensor

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 wo

Solution 1:

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

Solution 2:

You can do this with fill_lower_triangular:

import numpy as np
import tensorflow as tf
from tensorflow.python.ops.distributions.util import fill_lower_triangular
n = 4
coeffs = tf.constant(np.random.normal(0, 1, int(n*(n+1)/2)), dtype=tf.float64)
lower_diag = fill_lower_triangular(coeffs)

Post a Comment for "Packing Array Into Lower Triangular Of A Tensor"