Giovanni Barbarani
Giovanni Barbarani

Reputation: 239

Tensorflow: how to deal with dynamic shape trying to tile and concatenate two tensor?

I've two tensor, for example x = [1,2] and y=[3], and I want replicate the last along an axis of the other, obtaining z = [[1,3],[2,3]]. Ideally in tensorflow:

x = tf.placeholder(shape=[None, 2], dtype = tf.float32)
y = tf.placeholder(shape=[1], dtype = tf.float32)
z = tf.concat(x, tf.tile(y, [ x.shape[0] ]) , 1)

The problem is that x placeholder first dimension is not determined, how can I fix this?

Upvotes: 4

Views: 1942

Answers (1)

Prasad
Prasad

Reputation: 6034

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

x = tf.placeholder(shape=[None, 2], dtype = tf.float32)
y = tf.placeholder(shape=[1], dtype = tf.float32)

dim = tf.shape(x)[0]
y1 = tf.expand_dims(y, axis = 1)
y1 = tf.tile(y1, [dim, 1])
z = tf.concat((x, y1), axis = 1)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    z_val = sess.run(z, feed_dict = {x:[[2,5],[5,7],[8,9]], y:[3]})
    print(z_val)

Output:

[[ 2.  5.  3.]
 [ 5.  7.  3.]
 [ 8.  9.  3.]]

Upvotes: 1

Related Questions