admin管理员组

文章数量:1125715

I am trying to clone a batch intermediately. For example my input has shape (2,3) where 2 is batch-size. But I wish to create clones of this batch between Keras layers such that the new batch shape is (6,3) with the batch of size 2 repeated 3 times. Finally I wish to also reshape the new expanded batch to (2,3,3). How can I use Lambda to do this?

I am trying to clone a batch intermediately. For example my input has shape (2,3) where 2 is batch-size. But I wish to create clones of this batch between Keras layers such that the new batch shape is (6,3) with the batch of size 2 repeated 3 times. Finally I wish to also reshape the new expanded batch to (2,3,3). How can I use Lambda to do this?

Share Improve this question asked Jan 9 at 3:28 p__10p__10 436 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

One solution with a Lambda layer:

from tensorflow import keras
from keras import layers, models
import tensorflow as tf

def myfunc(x):
  res = tf.concat([x, x, x], axis=0)
  res = tf.reshape(res, (-1, x.shape[-1], x.shape[-1]))
  return res

inp = layers.Input(shape=(3,))
out_concat = layers.Lambda(lambda x: myfunc(x))(inp)
model = models.Model(inputs=inp, outputs=out_concat)
model.summary()

x = tf.constant([[1, 2, 3],
                 [4, 5, 6]])
res = model.predict([x])
print(res)

[[[1. 2. 3.]
  [4. 5. 6.]
  [1. 2. 3.]]

 [[4. 5. 6.]
  [1. 2. 3.]
  [4. 5. 6.]]]

本文标签: tensorflowHow do I clone batches in KerasStack Overflow