Concatenate input with constant vector in keras. h

2019-07-23 18:26发布

As a follow-up from this question:

Concatenate input with constant vector in keras

I am trying to use the suggested solution:

constant=K.variable(np.ones((1,10, 5)))
constant = K.repeat_elements(constant,rep=batch_size,axis=0)

And got the following Error:

NameError: name 'batch_size' is not defined

I do not see how one define within the keras model the batch_size [not explicitly] so that one can concatenate a symbolic layer and a constant layer in order to use them as an input layer.

1条回答
迷人小祖宗
2楼-- · 2019-07-23 19:09

To get the dynamic batch size:

batch_size = K.shape(your_tensor)[0]

But K.repeat_elements() doesn't accept Tensor values for rep. You can however produce the same result using K.tile():

from keras.models import *
from keras import backend as K
import numpy as np

a = Input(shape=(10, 5))
batch_size = K.shape(a)[0]
constant = K.variable(np.ones((1,10, 5)))
constant = K.tile(constant, (batch_size, 1, 1))
print(constant)
# Tensor("Tile:0", shape=(?, 10, 5), dtype=float32)
查看更多
登录 后发表回答