Tensorflow python: reshape input [batchsize] to tensor [batchsize, 2] with specific order

China☆狼群 提交于 2019-12-24 21:49:34

问题


I have a tensor (shape=[batchsize]). I want to reshape the tensor in a specific order and into shape=[-1,2]. But I want to have:

  1. Element at [0,0]
  2. Element at [1,0]
  3. Element at [0,1]
  4. Element at [1,1]
  5. Element at [0,2]
  6. Element at [0,3]
  7. Element at [2,1]
  8. Element at [3,1] and so on for an unknow batchsize.

Here is an example code with a tensor range=(0 to input=8).

import tensorflow as tf
import numpy as np

batchsize = tf.placeholder(shape=[], dtype=tf.int32)
x = tf.range(0, batchsize, 1) 
x = tf.reshape(x, shape=[2, -1])
y = tf.transpose(x)
z = tf.reshape(y, shape=[-1, 2])


input = 8
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    msg = sess.run([z], feed_dict={batchsize: input})
    print(msg)

Now my output is:

[array([[0, 4],
       [1, 5],
       [2, 6],
       [3, 7]], dtype=int32)]

But I want the output to be:

[array([[0, 2],
       [1, 3],
       [4, 6],
       [5, 7]], dtype=int32)]

Keep in mind I do not know how big batchsize is, I just set input= 8 for exemplary reason. Furthermore here I want to break the order after every 2nd element. In future I also would like to have this flexible. And in my real code the tensor ´x´ is no range array but complex random numbers, so you cannot sort in any way w.r.t. the values. I just made this code for a demonstration purpose.


回答1:


You could try

 tf.reshape(tf.matrix_transpose(tf.reshape(x, [-1, 2, 2])), [-1, 2])


来源:https://stackoverflow.com/questions/50899488/tensorflow-python-reshape-input-batchsize-to-tensor-batchsize-2-with-speci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!