Pymal
Pymal

Reputation: 244

How to concat a scalar to a 1D vector in Keras?

I have a Keras layer of Shape (None, 8) and I would like to append a single scalar (value = 1) to the end of the Tensor. However I haven't been successful.

Here is my code (simplified):

print(layers)
# Tensor("feature_layer_2_89/Relu:0", shape=(?, 8), dtype=float32)
pad_tensor = tf.constant([1.0])
concat = concatenate([layers, pad_tensor])

I get the following error:

ValueError: A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 8), (1,)]

EDIT: Basically I want to append a scalar (with the value of 1) to a vector. For example given a vector (1D Tensor) [1 3 3 0 2], how to produce [1 3 3 0 2 1], and I don't want to mess with the batch size which is None here.

Upvotes: 0

Views: 1551

Answers (1)

Pymal
Pymal

Reputation: 244

You could create the pad_tensor such that it has the rank 2 as @Psidom suggested. So first we need to get the batch_size as follows:

batch_size = tf.shape(layers)[0]
padding_tensor = tf.ones([batch_size, 1])

Now we can use concatenate function to concat the two Tensors:

concat = concatenate([layers, padding_tensor])

Upvotes: 1

Related Questions