问题
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:
- Element at [0,0]
- Element at [1,0]
- Element at [0,1]
- Element at [1,1]
- Element at [0,2]
- Element at [0,3]
- Element at [2,1]
- 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