Reputation: 103
I would like to concatenate two tensors by duplicating one of the tensor. For example, I have two tensors of shape [2, 2, 3] and [2, 3]. The result should be in the shape of [2, 2, 6].
t1 = [[[ 1, 1, 1], [2, 2, 2]],
[[ 3, 3, 3], [4, 4, 4]]]
t2 = [[ 5, 5, 5], [6, 6, 6]]
"""
t3 = # some tf ops
t3 should be
t3 = [[[ 1, 1, 1, 5, 5, 5], [2, 2, 2, 5, 5, 5]],
[[ 3, 3, 3, 6, 6, 6], [4, 4, 4, 6, 6, 6]]]
"""
So If the two tensors are of shape [10, 5, 8] and [10, 3], the result should be of shape [10, 5, 11].
UPDATED
Another example:
t1 = np.reshape(np.arange(3*4*5), [3,4,5])
t2 = np.reshape(np.arange(3*1*2), [3,2])
""""
t3 should be
[[[ 0., 1., 2., 3., 4., 0., 1.],
[ 5., 6., 7., 8., 9., 0., 1.],
[ 10., 11., 12., 13., 14., 0., 1.],
[ 15., 16., 17., 18., 19., 0., 1.]],
[[ 20., 21., 22., 23., 24., 2., 3.],
[ 25., 26., 27., 28., 29., 2., 3.],
[ 30., 31., 32., 33., 34., 2., 3.],
[ 35., 36., 37., 38., 39., 2., 3.]],
[[ 40., 41., 42., 43., 44., 4., 5.],
[ 45., 46., 47., 48., 49., 4., 5.],
[ 50., 51., 52., 53., 54., 4., 5.],
[ 55., 56., 57., 58., 59., 4., 5.]]]
"""
Upvotes: 1
Views: 1906
Reputation: 200
The function tf.tile
can help you make it. Click here to get detail of the function.
import numpy as np
import tensorflow as tf
t1 = np.reshape(np.arange(3*4*5), [3,4,5])
t2 = np.reshape(np.arange(3*1*2), [3,2])
# Keep t1 stay
t1_p = tf.placeholder(tf.float32, [3,4,5])
# Change t2 from shape(3,2) to shape(3,4,2) followed below two steps:
# 1. copy element of 2rd dimension of t2 as many times as you hope, as the updated example, it is 4
# 2. reshape the tiled tensor to compatible shape
t2_p = tf.placeholder(tf.float32, [3,2])
# copy the element of 2rd dimention of t2 by 4 times
t2_p_tiled = tf.tile(t2_p, [1, 4])
# reshape tiled t2 with shape(3,8) to the compatible shape(3,4,2)
t2_p_reshaped = tf.reshape(t2_p_tiled, [3,4,2])
# Concat t1 and changed t2, then you will get t3 you want
t3_p = tf.concat([t1_p, t2_p_reshaped], 2)
sess = tf.InteractiveSession()
t3 = sess.run(t3_p, {t1_p:t1, t2_p:t2})
print '*' * 20
print t1
print '*' * 20
print t2
print '*' * 20
print t3
# if you confused what the tf.tile did, you can print t2_p_tiled to see what happend
t2_tile = sess.run(t2_p_tiled, {t2_p:t2})
print '*' * 20
print t2_tile
Upvotes: 1
Reputation: 1143
You need to use the function pack https://www.tensorflow.org/api_docs/python/array_ops/slicing_and_joining#pack
The code should be something similar to this:
t2 = tf.transpose(t2)
tf.pack([t1, tf.pack(t2,t2, axis=1)], axis=2)
UPDATE
So If the two tensors are of shape [10, 5, 8] and [10, 3], the result should be of shape [10, 5, 11].
I am not sure this is possible. Can you write down how are this tensors and how the result tensor should be? The second dimension of the first and result tensors it is not something you can create from scratch for the second tensor.
Upvotes: 0