Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create triangular matrix in tensorflow

I want to create a N * N lower triangular matrix with a length N*(N+1)/2 vector. I find tensorflow has a function tf.contrib.distributions.fill_triangular that achieves my goal.

However when I give

from tensorflow.contrib.distributions import fill_triangular

it says

cannot import name fill_triangular

My tensorflow version is 1.4.1. Can anyone let me know where is fill_triangular or how to create a N * N lower triangular matrix with a length N*(N+1)/2 vector?

like image 541
Mingzhang Michael Yin Avatar asked Jan 05 '18 12:01

Mingzhang Michael Yin


Video Answer


1 Answers

fill_triangular is currently only available in the master version of Tensorflow (docs); it is not included even in the latest stable version 1.5 (docs), let alone 1.4.1.

You can build your matrix using numpy.tril_indices; here is an example with N=3:

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6]) # this is your N*(N+1)/2 vector
tri = np.zeros((3,3))  # initialize an NxN zero matrix
tri[np.tril_indices(3, 0)] = a
tri

the result is

array([[ 1.,  0.,  0.],
       [ 2.,  3.,  0.],
       [ 4.,  5.,  6.]])
like image 153
desertnaut Avatar answered Oct 02 '22 00:10

desertnaut