Keras Custom Merge Two Tensors

I have two tensors of shape [1,4] say,

[1,2,3,4] [0.2,0.3,0.4,0.5]

Now I want to merge them in merge layer (perhaps using some custom function using Tensorflow backend) so that they become

[1,0.2,2,0.3,3,0.4,4,0.5]

How can I achieve this? The shape of the tensor is fixed. Thank you for your time.

Upvotes: 2

Views: 1551

Answers (2)

nessuno
nessuno

Reputation: 27042

A possible solution is to concatenate the tensors along the axis 0 and then gather the values according to the indices, like that

import tensorflow as tf
from itertools import chain

A = tf.constant([1, 2, 3, 4])
B = tf.constant([0.2, 0.3, 0.4, 0.5])

# Cast A to be compatible with B
A = tf.cast(A, tf.float32)

# Concat AB one next to the other
AB = tf.concat([A, B], axis=0)

# Generate a list of values in this sequence
# 0, 4, 1, 5, ... in other to indicize the tensors
# use gather to collect values in the specified positions
NEW = tf.gather(AB,
                list(
                    chain.from_iterable((i, i + A.shape[0].value)
                                        for i in range(A.shape[0].value))))

with tf.Session() as sess:
    print(sess.run([NEW]))

Upvotes: 2

Manolo Santos
Manolo Santos

Reputation: 1913

Using Tensorflow, you can use reshape and concat. These operations are also available in the keras backend.

a = tf.constant([1,2,3,4])
b = tf.constant([10,20,30,40])

c = tf.reshape(tf.concat([tf.reshape(a,(-1,1)), tf.reshape(b, (-1,1))], 1), (-1,))

I don't know if there exists a more straightforward way to accomplish this.

Edit: There exists a simpler solution using tf.stack instead of tf.concat.

c = tf.reshape(tf.stack([a, b], 1),(-1,))

Upvotes: 2

Related Questions