Reputation: 636
I have an input tensor which represents an alternation between item and item quantity:
[item0, qty0, item1, qty1, ...]
I would like to unfold this tensor to
[[item0*qty0], [item1*qty1], ...]
Example:
[1000, 2, 3000, 5, ...]
[[100,1000], [3000,3000,3000,3000,3000], ...]
This is in tensorflow 1.x btw.
Upvotes: 0
Views: 369
Reputation: 636
I started with the answer given by zihaozhihao, but since input has dimensions (?) the length is not known and hence tf.unstack won't work.
However, one of the error messages recommended using map_fn and that seems to work:
x_unpacked = tf.reshape(input, (-1, 2))
tiled = tf.map_fn(lambda x: tf.tile([x[0]], [x[1]]), x_unpacked)
Upvotes: 0
Reputation: 4475
In tf1.x version.
import tensorflow as tf
inputs = tf.constant([10,2,20,3,30,4])
x_unpacked = tf.unstack(tf.reshape(inputs,(-1,2)))
tmp = []
for t in x_unpacked:
tmp.append(tf.tile([t[0]], [t[1]]))
ans = tf.concat(tmp, axis=0)
with tf.Session() as sess:
print(sess.run(ans))
# [10 10 20 20 20 30 30 30 30]
In tf2.x, it can be one line,
tf.concat([tf.tile([x[0]],[x[1]]) for x in tf.reshape(inputs, (-1,2))], axis=0)
# [10 10 20 20 20 30 30 30 30]
Upvotes: 1