Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow (Python): How to append a scalar to each row in a tensor

If I have a 2-d tensor with the first dimension being dynamic, how can I append a scalar value to the end of each row?

So if I feed [[1,2], [3,4]] to a tensor, I want to make it [[1,2,5], [3,4,5]].

Example (doesn't work):

a = tf.placeholder(tf.int32, shape=[None, 2])
b = tf.concat([tf.constant(5), a], axis=1)

This gives me: ValueError: Can't concatenate scalars (use tf.stack instead) for 'concat_3' (op: 'ConcatV2') with input shapes: [], [?,2], [].

I assume this needs some combination of tf.stack, tf.tile, and tf.shape, but I can't seem to get it right.

like image 737
ahbutfore Avatar asked Nov 07 '22 04:11

ahbutfore


1 Answers

IMO padding is the easiest way here:

a = tf.placeholder(tf.int32, shape=[None, 2])
b = tf.pad(a, [[0, 0], [0, 1]], constant_values=5)

will append a 5-column.

Documentation: tf.pad.

like image 128
hoefling Avatar answered Nov 14 '22 20:11

hoefling