Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TensorFlow tf.reshape Fortran order (like numpy)

Does TensorFlow provide a way to reshape a tensor in Fortran (column-major order? NumPy allows:

a = ...
np.reshape(a, (32, 32, 3), order='F')

I'm trying to reshape CIFAR images to be 32x32x3 (from a vector of shape 3072x1), but I'm getting images that look like this:

Example CIFAR image

Using Fortran order in Numpy solves the problem, but I need to do the same in TensorFlow.

Edit: I realize now that I can get the correct output by reshaping to 3x32x32 and then transposing the output. I'm still a bit surprised that TF doesn't provide out of the box reshaping in either row-major or column-major order.

like image 482
eric.mitchell Avatar asked May 28 '17 03:05

eric.mitchell


1 Answers

Tensorflow does not seem to support Fortran (Column-Major) ordering, but there is a simple solution. You have to combine reshape with transpose. The code below uses numpy to show the equivalent operations followed by the Tensorflow version.

Numpy:

>>> import numpy as np
>>> want = np.arange(12).reshape((4,3),order='F')
>>> want
array([[ 0,  4,  8],
       [ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11]])
>>> have = np.arange(12).reshape((3,4))
>>> have
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> have.transpose()
array([[ 0,  4,  8],
       [ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11]])

Tensorflow: (assumes you want MxN in the end)

want = tf.transpose(tr.reshape(input,(n,m)))
like image 140
David Avatar answered Sep 29 '22 05:09

David