Python – Creates a matrix with dimension [N,D] from a tensor of dimension [N].

Creates a matrix with dimension [N,D] from a tensor of dimension [N]…. here is a solution to the problem.

Creates a matrix with dimension [N,D] from a tensor of dimension [N].

I

have an N-dimensional tensor and I want to duplicate it to create an NxD dimensional tensor with each column being the initial vector.

Thanks

Solution

You first want to expand the tensor/reshape to an N x 1 shape and then tile it D times in two dimensions:

tensor_N_x_1 = tf.expand_dims(tensor, 1)     # Expand by adding a dim in position 1
tensor_N_x_D = tf.tile(tensor_N_x_1, [1, D]) # Tile 1 time in the 1st dim, D times in the 2nd

Documentation:

Related Problems and Solutions