简体   繁体   中英

Reshaping a Tensor in TensorFlow with scalar tensors

I have a tensor, X of shape (T, n, k) .

If I knew the shape beforehand, it is easy to reshape, tf.reshape(X, (T * n, k)) where T, n, k are ints, not tensors. But is there a way to do this if I don't know the shapes. It seems that getting the shapes like shape = tf.shape(X) and reshaping doesn't work. That is,

tf.reshape(X, (tf.shape[0] * tf.shape[1], tf.shape[2]))

Any ideas? In my application, T and k are known before runtime but n is only known at runtime.

Take a look at this:

import tensorflow as tf

a, b, c = 2, 3, 4
x = tf.Variable(tf.random_normal([a, b, c], mean=0.0, stddev=1.0, dtype=tf.float32))
s = tf.shape(x)

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
v1, v2, v3 = sess.run(s)
y = tf.reshape(x, [v1 * v2, v3])
shape = tf.shape(y)

print sess.run(y)
print sess.run(shape)

I am getting the shape of the variable after it's initialization and then use it later. Also take a look at this answer , as it deals with a similar thing.

Now that you told that you use placeholders to populate data, it started to make sense. Here is an example of how can you reshape your data in this case:

import tensorflow as tf
import numpy as np
data = np.random.rand(2, 3, 4)

x = tf.placeholder("float", None)
s = tf.shape(x)

sess = tf.Session()
shape_original = sess.run(s, feed_dict={x: data})

x_ = tf.reshape(x, [shape_original[0] * shape_original[1], shape_original[2]])
s_ = tf.shape(x_)

shape_now = sess.run(s_, feed_dict={x: data})
print 'Original\t', shape_original
print 'Now\t\t\t', shape_now

sess.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM